繁体   English   中英

有没有办法将可选参数传递给函数?

[英]Is there a way to pass optional parameters to a function?

Python 中是否有一种方法可以在调用函数时将可选参数传递给函数,并且在函数定义中有一些基于“仅当传递可选参数时”的代码

Python 2 文档, 7.6。 函数定义为您提供了几种方法来检测调用者是否提供了可选参数。

首先,您可以使用特殊的形式参数语法* 如果函数定义的形式参数前面有一个* ,则 Python 会使用与前面的形式参数(作为元组)不匹配的任何位置参数填充该参数。 如果函数定义有一个以**开头的形式参数,则 Python 会使用与前面的形式参数(作为 dict)不匹配的任何关键字参数填充该参数。 该函数的实现可以检查这些参数的内容,以查找您想要的任何“可选参数”。

例如,这里有一个函数opt_fun ,它接受两个位置参数x1x2 ,并查找另一个名为“可选”的关键字参数。

>>> 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

其次,您可以提供某个值的默认参数值,例如调用者永远不会使用的None 如果参数有这个默认值,你就知道调用者没有指定参数。 如果参数有一个非默认值,你就知道它来自调用者。

def my_func(mandatory_arg, optional_arg=100):
    print(mandatory_arg, optional_arg)

http://docs.python.org/2/tutorial/controlflow.html#default-argument-values

我发现这比使用**kwargs更具可读性。

为了确定是否传递了一个参数,我使用自定义实用程序对象作为默认值:

MISSING = object()

def func(arg=MISSING):
    if arg is MISSING:
        ...
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. 

如果你想给一个参数赋予一些默认值,请在 () 中赋值。 像(x = 10)。 但重要的是首先应该强制参数然后是默认值。

例如。

(y, x = 10)

(x=10, y) 是错误的

您可以使用永远不会传递给函数的内容为可选参数指定默认值,并使用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)

那么只要你不做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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM