简体   繁体   English

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

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

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

The Python 2 documentation, 7.6. Python 2 文档, 7.6。 Function definitions gives you a couple of ways to detect whether a caller supplied an optional parameter. 函数定义为您提供了几种方法来检测调用者是否提供了可选参数。

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).如果函数定义的形式参数前面有一个* ,则 Python 会使用与前面的形式参数(作为元组)不匹配的任何位置参数填充该参数。 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).如果函数定义有一个以**开头的形式参数,则 Python 会使用与前面的形式参数(作为 dict)不匹配的任何关键字参数填充该参数。 The function's implementation can check the contents of these parameters for any "optional parameters" of the sort you want.该函数的实现可以检查这些参数的内容,以查找您想要的任何“可选参数”。

For instance, here's a function opt_fun which takes two positional parameters x1 and x2 , and looks for another keyword parameter named "optional".例如,这里有一个函数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

Second, you can supply a default parameter value of some value like None which a caller would never use.其次,您可以提供某个值的默认参数值,例如调用者永远不会使用的None 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.如果参数有一个非默认值,你就知道它来自调用者。

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

If you want give some default value to a parameter assign value in ().如果你想给一个参数赋予一些默认值,请在 () 中赋值。 like (x =10).像(x = 10)。 But important is first should compulsory argument then default value.但重要的是首先应该强制参数然后是默认值。

eg.例如。

(y, x =10) (y, x = 10)

but

(x=10, y) is wrong (x=10, y) 是错误的

You can specify a default value for the optional argument with something that would never passed to the function and check it with the is operator:您可以使用永远不会传递给函数的内容为可选参数指定默认值,并使用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)

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

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