[英]Vary different parameters each time I call a function in Python
I have a function 我有一个功能
def input_definition(parameter_variation=None):
input_def = {}
input_def['a'] = 1
input_def['b'] = 2
input_def['c'] = 3
...
input_def['z'] = 26
# Apply the parameter variation by means of the input argument 'parameter_variation'.
# ...
# Save 'input_def' to external file with dill module.
# ...
with many parameters. 有很多参数。 I want to vary some of these parameters by giving parameter_variation
to the function input_definition
. 我想通过给函数input_definition
提供parameter_variation
来改变其中一些参数。 I need to vary different parameters each time I call input_definition
. 每次调用input_definition
时,我都需要改变不同的参数。
So one time parameter_variation
contains values for a
and b
and another time parameter_variation
contains values for c
and d
. 因此,一个时间parameter_variation
包含a
和b
值,而另一个时间parameter_variation
包含c
和d
值。
What is the best / most neat / Pythonic way to do this? 什么是最好/最整洁/ Pythonic的方法? Or is it perhaps better to use kwargs? 还是使用kwargs更好?
You can use kwargs
for this like so: 您可以这样使用kwargs
:
def some_func(**kwargs):
my_dict = dict(
a=1,
b=2,
c=3,
d=4
)
my_dict.update(**kwargs)
This will set your defaults and then override them with kwargs. 这将设置您的默认值,然后用kwargs覆盖它们。
It is arguable better to give more limited inputs to the dict by simply using default arguments like so: 可以通过简单地使用默认参数为dict提供更多有限的输入,这是有争议的:
def some_func(a=1, b=2, c=3, d=4):
my_dict = dict(
a=a,
b=b,
c=c,
d=d
)
This is more secure and makes your intentions more understandable to someone reading your code. 这样更安全,并使您的意图对于阅读您的代码的人来说更容易理解。 But is less flexible in comparison to kwargs
. 但与kwargs
相比,灵活性较差。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.