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

时间:2022-06-07 11:03:35

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中是否有一种方法可以在调用函数时将可选参数传递给函数,并且在函数定义中有一些代码基于“只有传递了可选参数”

5 个解决方案

#1


91  

The Python 2 documentation, 7.6. Function definitions gives 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_fun which takes two positional parameters x1 and x2, and looks for another keyword parameter named "optional".

例如,这是一个函数opt_fun,它接受两个位置参数x1和x2,并查找另一个名为“optional”的关键字参数。

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

其次,您可以提供某些值的默认参数值,如“调用者”永远不会使用的值。如果参数具有此默认值,则您知道调用者未指定参数。如果参数具有非默认值,则表示它来自调用者。

#2


55  

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

#3


17  

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. 

#4


5  

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)是错误的

#5


2  

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)

#1


91  

The Python 2 documentation, 7.6. Function definitions gives 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_fun which takes two positional parameters x1 and x2, and looks for another keyword parameter named "optional".

例如,这是一个函数opt_fun,它接受两个位置参数x1和x2,并查找另一个名为“optional”的关键字参数。

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

其次,您可以提供某些值的默认参数值,如“调用者”永远不会使用的值。如果参数具有此默认值,则您知道调用者未指定参数。如果参数具有非默认值,则表示它来自调用者。

#2


55  

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

#3


17  

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. 

#4


5  

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)是错误的

#5


2  

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)