[英]Defining default keyword values to function in a dictionary in python
I am writing a function that takes a lot of keywords.我正在写一个需要很多关键字的 function。
I have a dictionary which is very lengthy that contains many of these keywords that already exists in my code and is being used elsewhere.我有一本很长的字典,其中包含许多已经存在于我的代码中并且正在其他地方使用的关键字。 Eg
例如
{'setting1':None, 'setting2': None....}
I am wondering is there a way, when I define my function, for me to set all of these as keywords, rather than having to type them out again like this:我想知道有没有一种方法,当我定义我的 function 时,我可以将所有这些设置为关键字,而不必像这样再次输入它们:
def my_function(setting1=None, setting2=None, **kwargs)
To be clear, essentially I want to set all of the contents of the dictionary to be keywords with default value None, and when I call the function I should be able to change their values.需要明确的是,基本上我想将字典的所有内容设置为默认值为 None 的关键字,当我调用 function 时,我应该能够更改它们的值。 So I am not looking to provide the dictionary as kwargs upon calling the function.
所以我不打算在调用 function 时将字典作为 kwargs 提供。
While not exactly the same, I ususally prefer to save the arguments in **kwargs
and use .get()
to get the value or None
:虽然不完全相同,但我通常更喜欢将 arguments 保存在
**kwargs
中并使用.get()
获取值或None
:
def my_function(**kwargs):
do_something(kwargs.get("alpha"), kwargs.get("beta"))
.get()
on a dictionary returns the value if a key exists, or None
of it does not.如果键存在,则字典上的
.get()
返回值,或者None
一个键不存在。 You can optionally specify a different default value as a second argument if you like.如果愿意,您可以选择指定不同的默认值作为第二个参数。
When creating a function, you will need to implement how your arguments are used.创建 function 时,您需要实现 arguments 的使用方式。 By automatically creating arguments you end up adding arguments and forgetting to implement a behaviour for them.
通过自动创建 arguments 您最终会添加 arguments 并忘记为它们实现行为。
# Manually defined.
def func(a, b, c, d):
return a + b / c * d
# Auto-defined - Human error.
def func(""" auto define a,b,c,d,e,f,g,h """):
return a + b / c * d # <- you only use half of the arguments. Confusing at best.
# Auto-defined - Inputs unclear, code is not explicit.
def func(defind_my_args):
return a + b / c * d
If you need to reuse "code behaviour" to the point that you can "inherit" parameters, maybe you should be using an object instead.如果您需要重用“代码行为”到可以“继承”参数的程度,也许您应该改用 object。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.