在函数中传递可选参数 - python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35265234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing an optional argument in a function - python
提问by Kfir Cohen
I would like to create a function which can take either 1 or 2 arguments. Currently, I have a function which takes exactly 2 arguments through CMD:
我想创建一个可以接受 1 或 2 个参数的函数。目前,我有一个函数,它通过 CMD 正好接受 2 个参数:
def test(self,countName,optionalArg):
if countName == "lowest":
#something
if optionalArg == "furthest:
#something
else:
#something else
if __name__ == '__main__':
countName = sys.argv[1]
optionalArg = sys.argv[2]
temp = len(sys.argv)
for i in xrange(1,temp):
sys.argv.pop()
I would then run:
然后我会运行:
python filename.py lowest furthest
python filename.py 最低最远
Using this means that passing the second arg is a must. If I try to run my script just by passing one arg, it encounters an error (as expected). My question is, how do you create an optional argument, which could either be passed or not, depending on the situation?
使用这意味着必须传递第二个参数。如果我尝试仅通过传递一个 arg 来运行我的脚本,则会遇到错误(如预期)。我的问题是,你如何创建一个可选参数,根据情况可以传递或不传递?
For example:
例如:
python filename.py lowest
python 文件名.py 最低
In this situation, I expect the program to perform the "#something else" script, as nothing was passed and it is different than "furthest".
在这种情况下,我希望程序执行“#something else”脚本,因为没有传递任何内容并且它与“最远”不同。
Please do not write the code for me, I am here to learn :)
请不要为我写代码,我是来学习的:)
采纳答案by bruno desthuilliers
This is explained in the FineManual(tm): https://docs.python.org/2/tutorial/controlflow.html#more-on-defining-functions
这在 FineManual(tm) 中有解释:https://docs.python.org/2/tutorial/controlflow.html#more-on-defining-functions
Note that in Python, the expression defining the default value for an optional argument is eval'd ony once when the def
statement is executed (which is at first import for a top-level function), which can lead to unexpected behaviours (cf "Least Astonishment" and the Mutable Default Argument).
请注意,在 Python 中,定义可选参数的默认值的表达式在def
执行语句时会被 eval 一次(这是顶级函数的第一次导入),这可能导致意外行为(参见“Least惊讶”和可变默认参数)。
Also, the "default value" has to be an expression, not a statement, so you cannot do any error handling here. wrt/ your case with trying to use sys.argv[2]
as a default value, it's wrong for at least two reasons:
此外,“默认值”必须是表达式,而不是语句,因此您不能在此处进行任何错误处理。wrt/你的情况试图sys.argv[2]
用作默认值,至少有两个原因是错误的:
- as you already noticed, it breaks if
len(sys.argv) < 3
- it makes your function dependent on
sys.argv
, so you cannot reuse it in a different context
- 正如您已经注意到的那样,如果
len(sys.argv) < 3
- 它使您的函数依赖于
sys.argv
,因此您不能在不同的上下文中重用它
The right solution here is to handle all user input (sys.argv
or whatever) in the "entry point" code (the __main__
section) - your function should know nothing about where the arguments values came from (sys.argv
, an HTTP request, a text file or whatever).
这里正确的解决方案是处理sys.argv
“入口点”代码(该__main__
部分)中的所有用户输入(或其他任何内容)-您的函数应该不知道参数值来自何处(sys.argv
、HTTP 请求、文本文件或其他任何内容) .
So to make a long story short: use either a hardcoded value (if it makes sense) or a "sentinel" value (None
is a good candidate) as default value for your optional argument, and do all the user inputs parsing in the __main__
section (or even better in a main()
function called from the __main__
section so you don't pollute the module's namespace with irrelevant variables):
因此,长话短说:使用硬编码值(如果有意义)或“哨兵”值(None
是一个很好的候选者)作为可选参数的默认值,并在__main__
部分中解析所有用户输入(或者甚至在main()
从该__main__
部分调用的函数中更好,这样您就不会用不相关的变量污染模块的命名空间):
def func(arg, optarg=None):
#code here
def main(*args):
#parse args
#call func with the right args
if __name__ == "__main__":
import sys
main(*sys.argv)
回答by Dharmik
You can write your function by providing default argument value to the argument you want to ignore like optionalArg=None(whatever you want) by doing this you can call the function with single argument.
您可以通过为要忽略的参数提供默认参数值来编写函数,例如 optionalArg=None(whatever you want) 通过这样做,您可以使用单个参数调用该函数。
回答by k4ppa
A very, VERY ugly way is to use exceptions for check if the parameter is defined:
一种非常非常丑陋的方法是使用异常来检查参数是否已定义:
import sys
if __name__ == '__main__':
arg = sys.argv[1]
try:
optionalArg = sys.argv[2]
except IndexError:
optionalArg = ""
else:
print "sure, it was defined."
I advise you not to use it, because you should never be in a situation where you don't know if a variable is defined or not, there are better ways to handle this, but in some cases (not yours) can be usefull, I add it only for this reason.
我建议你不要使用它,因为你永远不应该处于不知道变量是否定义的情况,有更好的方法来处理这个问题,但在某些情况下(不是你的)可能很有用,我只是因为这个原因添加它。
回答by Device
Something like this? kinda code sorry :D
像这样的东西?有点代码抱歉:D
def function(value, opt = ""):
print("Value: " + value)
if not opt == "":
print("Optional: " + opt)
回答by Supahupe
You can pass a dictionary. Or a default value which is None if you not explicitly initialize it when calling the function.
您可以传递字典。或者如果您在调用函数时没有明确初始化它,则默认值为 None 。
回答by Maxim Panfilov
Variant:
变体:
def somefunc(*args, **kwargs):
if 'optional_arg' in kwargs:
print kwargs['optional_arg']
回答by Pouria
You can use *args
to pass any number of arguments and receive them as a list, or use **kwargs
to send keyword arguments and receive them as a dictionary.
您可以使用*args
传递任意数量的参数并将它们作为列表接收,或者使用**kwargs
发送关键字参数并作为字典接收它们。
Here is an example for *args
:
下面是一个例子*args
:
def test(count_name, *args):
if count_name == "lowest":
print('count_name received.')
if args and args[-1] == "furthest":
print('2nd arg received.')
else:
print('No second arg given.')
return None
if __name__ == '__main__':
count_name = 'lowest'
optional_arg = 'furthest'
print('Test 1:')
test(count_name, optional_arg)
# Displays:
# Test 1:
# count_name received.
# 2nd arg received.
print('\n\nTest 2:')
test(count_name)
# Test 2:
# count_name received.
# No second arg given.
This is how you pass optional arguments, not by defining a default value for a variable, which initialises the variable in the memory.
这就是您传递可选参数的方式,而不是通过为变量定义默认值来初始化内存中的变量。