带有 **kwargs 的函数
Functions with **kwargs
我想编写一个 Python 函数 myfun
,它只接受可选参数,a
和 b
。
如果在调用 myfun
时未指定 a
或 b
之一,我如何告诉 myfun
使用某些默认值 a
和 b
?
def myfun(**kwargs):
a = kwargs.get('a', None)
# if a is not specified, use default a=4.4
b = kwargs.get('b', None)
# if b is not specified, use default b=2.1
c = 2*a
d = 3.1*b
return c, d
c,d = myfun(a=1,b=2)
print c,d
**kwargs
用于收集任意数量 的关键字参数。如果您只想接受两个,那么它不是正确的工具。
相反,您应该为 a
和 b
参数指定默认值:
def myfun(a=4.4, b=2.1):
演示:
>>> def myfun(a=4.4, b=2.1):
... print('a={}\nb={}'.format(a, b))
...
>>> myfun()
a=4.4
b=2.1
>>> myfun(a=1)
a=1
b=2.1
>>> myfun(a=1, b=2)
a=1
b=2
>>> myfun(b=2)
a=4.4
b=2
>>>
将它们设置为默认值:
def myfun(a=4.4,b=2.1):
如果您没有将它们作为关键字添加到函数定义中,用户将无法知道他们可以设置 a
和 b
。
如果您使用 kwargs.get
设置一个值,您将传递默认值以获得:
a = kwargs.get('a', 4.4) # a = 4.4 if a not in kwargs
b = kwargs.get('b', 2.1)
我想编写一个 Python 函数 myfun
,它只接受可选参数,a
和 b
。
如果在调用 myfun
时未指定 a
或 b
之一,我如何告诉 myfun
使用某些默认值 a
和 b
?
def myfun(**kwargs):
a = kwargs.get('a', None)
# if a is not specified, use default a=4.4
b = kwargs.get('b', None)
# if b is not specified, use default b=2.1
c = 2*a
d = 3.1*b
return c, d
c,d = myfun(a=1,b=2)
print c,d
**kwargs
用于收集任意数量 的关键字参数。如果您只想接受两个,那么它不是正确的工具。
相反,您应该为 a
和 b
参数指定默认值:
def myfun(a=4.4, b=2.1):
演示:
>>> def myfun(a=4.4, b=2.1):
... print('a={}\nb={}'.format(a, b))
...
>>> myfun()
a=4.4
b=2.1
>>> myfun(a=1)
a=1
b=2.1
>>> myfun(a=1, b=2)
a=1
b=2
>>> myfun(b=2)
a=4.4
b=2
>>>
将它们设置为默认值:
def myfun(a=4.4,b=2.1):
如果您没有将它们作为关键字添加到函数定义中,用户将无法知道他们可以设置 a
和 b
。
如果您使用 kwargs.get
设置一个值,您将传递默认值以获得:
a = kwargs.get('a', 4.4) # a = 4.4 if a not in kwargs
b = kwargs.get('b', 2.1)