Python 有没有办法将可选参数传递给函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14017996/
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
Is there a way to pass optional parameters to a function?
提问by user1795998
Is there a way in Python to pass optional parameters to a function while calling it and in the function definition have some code based on "only if the optional parameter is passed"
Python 中是否有一种方法可以在调用函数时将可选参数传递给函数,并且在函数定义中有一些基于“仅当传递可选参数时”的代码
采纳答案by Jim DeLaHunt
The Python 2 documentation, 7.6. Function definitionsgives you a couple of ways to detect whether a caller supplied an optional parameter.
在Python 2中的文档,7.6。函数定义为您提供了几种方法来检测调用者是否提供了可选参数。
First, you can use special formal parameter syntax *. If the function definition has a formal parameter preceded by a single *, then Python populates that parameter with any positional parameters that aren't matched by preceding formal parameters (as a tuple). If the function definition has a formal parameter preceded by **, then Python populates that parameter with any keyword parameters that aren't matched by preceding formal parameters (as a dict). The function's implementation can check the contents of these parameters for any "optional parameters" of the sort you want.
首先,您可以使用特殊的形参语法*。如果函数定义的形式参数前面有单个*,则 Python 会使用与前面的形式参数(作为元组)不匹配的任何位置参数填充该参数。如果函数定义有一个以 开头的形式参数**,则 Python 会使用与前面的形式参数不匹配的任何关键字参数(作为 dict)填充该参数。该函数的实现可以检查这些参数的内容以查找您想要的任何“可选参数”。
For instance, here's a function opt_funwhich takes two positional parameters x1and x2, and looks for another keyword parameter named "optional".
例如,这里有一个函数opt_fun,它接受两个位置参数x1和x2,并查找另一个名为“可选”的关键字参数。
>>> def opt_fun(x1, x2, *positional_parameters, **keyword_parameters):
... if ('optional' in keyword_parameters):
... print 'optional parameter found, it is ', keyword_parameters['optional']
... else:
... print 'no optional parameter, sorry'
...
>>> opt_fun(1, 2)
no optional parameter, sorry
>>> opt_fun(1,2, optional="yes")
optional parameter found, it is yes
>>> opt_fun(1,2, another="yes")
no optional parameter, sorry
Second, you can supply a default parameter value of some value like Nonewhich a caller would never use. If the parameter has this default value, you know the caller did not specify the parameter. If the parameter has a non-default value, you know it came from the caller.
其次,您可以提供None调用者永远不会使用的某个值的默认参数值。如果参数有这个默认值,你就知道调用者没有指定参数。如果参数有一个非默认值,你就知道它来自调用者。
回答by warvariuc
def my_func(mandatory_arg, optional_arg=100):
print(mandatory_arg, optional_arg)
http://docs.python.org/2/tutorial/controlflow.html#default-argument-values
http://docs.python.org/2/tutorial/controlflow.html#default-argument-values
I find this more readable than using **kwargs.
我发现这比使用**kwargs.
To determine if an argument was passed at all, I use a custom utility object as the default value:
为了确定是否传递了一个参数,我使用自定义实用程序对象作为默认值:
MISSING = object()
def func(arg=MISSING):
if arg is MISSING:
...
回答by sumit
If you want give some default value to a parameter assign value in (). like (x =10). But important is first should compulsory argument then default value.
如果你想给一个参数指定一些默认值,请在 () 中赋值。像(x = 10)。但重要的是首先应该强制参数然后是默认值。
eg.
例如。
(y, x =10)
(y, x = 10)
but
但
(x=10, y) is wrong
(x=10, y) 是错误的
回答by Sanyal
def op(a=4,b=6):
add = a+b
print add
i)op() [o/p: will be (4+6)=10]
ii)op(99) [o/p: will be (99+6)=105]
iii)op(1,1) [o/p: will be (1+1)=2]
Note:
If none or one parameter is passed the default passed parameter will be considered for the function.
回答by Tadhg McDonald-Jensen
You can specify a default value for the optional argument with something that would never passed to the function and check it with the isoperator:
您可以使用永远不会传递给函数的内容为可选参数指定默认值,并使用is运算符检查它:
class _NO_DEFAULT:
def __repr__(self):return "<no default>"
_NO_DEFAULT = _NO_DEFAULT()
def func(optional= _NO_DEFAULT):
if optional is _NO_DEFAULT:
print("the optional argument was not passed")
else:
print("the optional argument was:",optional)
then as long as you do not do func(_NO_DEFAULT)you can be accurately detect whether the argument was passed or not, and unlike the accepted answer you don't have to worry about side effects of ** notation:
那么只要你不这样做,func(_NO_DEFAULT)你就可以准确地检测参数是否通过,并且与接受的答案不同,你不必担心 ** 符号的副作用:
# these two work the same as using **
func()
func(optional=1)
# the optional argument can be positional or keyword unlike using **
func(1)
#this correctly raises an error where as it would need to be explicitly checked when using **
func(invalid_arg=7)

