在 Python 中使用 **kwargs 的正确方法 [英] Proper way to use **kwargs in Python
问题描述
当涉及到默认值时,在 Python 中使用 **kwargs
的正确方法是什么?
What is the proper way to use **kwargs
in Python when it comes to default values?
kwargs
返回一个字典,但设置默认值的最佳方法是什么,或者有没有?我应该将它作为字典访问吗?使用获取功能?
kwargs
returns a dictionary, but what is the best way to set default values, or is there one? Should I just access it as a dictionary? Use get function?
class ExampleClass:
def __init__(self, **kwargs):
self.val = kwargs['val']
self.val2 = kwargs.get('val2')
一个简单的问题,但我找不到好的资源.在我见过的代码中,人们以不同的方式执行此操作,而且很难知道该使用什么.
A simple question, but one that I can't find good resources on. People do it different ways in code that I've seen and it's hard to know what to use.
推荐答案
对于不在字典中的键,您可以将默认值传递给 get()
:
You can pass a default value to get()
for keys that are not in the dictionary:
self.val2 = kwargs.get('val2',"default value")
但是,如果您打算使用具有特定默认值的特定参数,为什么不首先使用命名参数?
However, if you plan on using a particular argument with a particular default value, why not use named arguments in the first place?
def __init__(self, val2="default value", **kwargs):
这篇关于在 Python 中使用 **kwargs 的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!