当涉及到默认值时,在 Python 中使用 **kwargs
的正确方法是什么?
kwargs
返回一个字典,但是设置默认值的最佳方法是什么,或者有没有?我应该将它作为字典访问吗?使用get函数?
class ExampleClass:
def __init__(self, **kwargs):
self.val = kwargs['val']
self.val2 = kwargs.get('val2')
一个简单的问题,但我找不到好的资源。人们在我见过的代码中以不同的方式进行操作,很难知道该使用什么。
While most answers are saying that, e.g.,
is "the same as"
this is not true. In the latter case,
f
can be called asf(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.The idiom is so important that in Python 3 it now has special supporting syntax: every argument after a single
*
in thedef
signature is keyword-only, that is, cannot be passed as a positional argument, but only as a named one. So in Python 3 you could code the above as:Indeed, in Python 3 you can even have keyword-only arguments that aren't optional (ones without a default value).
However, Python 2 still has long years of productive life ahead, so it's better to not forget the techniques and idioms that let you implement in Python 2 important design ideas that are directly supported in the language in Python 3!