当涉及到默认值时,在Python中使用**kwargs的正确方法是什么?
Kwargs返回一个字典,但是设置默认值的最佳方法是什么?我应该把它作为字典来访问吗?使用get函数?
class ExampleClass:
def __init__(self, **kwargs):
self.val = kwargs['val']
self.val2 = kwargs.get('val2')
一个简单的问题,但我找不到好的资料。在我所见过的代码中,人们用不同的方式来实现它,很难知道该用什么。
虽然大多数答案都是这样说的,例如,
def f(**kwargs):
foo = kwargs.pop('foo')
bar = kwargs.pop('bar')
...etc...
是"the same as"
def f(foo=None, bar=None, **kwargs):
...etc...
this is not true. In the latter case, f can be called as f(23, 42), while the former case accepts named arguments only -- no positional calls. Often you want to allow the caller maximum flexibility and therefore the second form, as most answers assert, is preferable: but that is not always the case. When you accept many optional parameters of which typically only a few are passed, it may be an excellent idea (avoiding accidents and unreadable code at your call sites!) to force the use of named arguments -- threading.Thread is an example. The first form is how you implement that in Python 2.
这个习语非常重要,以至于在Python 3中,它现在有了特殊的支持语法:def签名中单个*后面的每个参数都是仅关键字参数,也就是说,不能作为位置参数传递,而只能作为命名参数传递。所以在Python 3中,你可以将上面的代码编写为:
def f(*, foo=None, bar=None, **kwargs):
...etc...
实际上,在Python 3中,你甚至可以有非可选的关键字参数(没有默认值的参数)。
然而,Python 2仍然有很长的生产寿命,所以最好不要忘记让你在Python 2中实现重要的设计思想的技术和习语,这些思想在Python 3中直接得到语言的支持!