在Python中,有没有一种方法可以在调用函数时将可选参数传递给函数,并且在函数定义中有一些基于“只有在传递可选参数时”的代码
发布于 2012-12-24 14:43:07
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:
...
发布于 2015-06-30 21:08:00
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.
发布于 2012-12-24 14:49:04
如果您想给参数指定一些默认值,请在()中赋值。如(x =10)。但重要的是首先应该强制参数,然后是默认值。
例如:
(y,x =10)
但
(x=10,y)错误
https://stackoverflow.com/questions/14017996
复制相似问题