【发布时间】:2011-01-31 00:08:14
【问题描述】:
假设我有,
class example(object)
def __init__(var1 = 10, var2 = 15, var3 = 5)
do a few things here
Other methods here
还有其他与问题无关的类。
为了研究系统的行为,我改变了上述__init__ 方法中的输入,一次一个。我有另一个函数start_simulation 函数,它将我想要更改为string 的输入名称及其可能的值。 (它使用这个名称和值来创建存储执行结果的文件名)。例如,我有
def start_simulation(var_under_study, var_under_study_values):
'''type of var_under_study: string'''
for value in var_under_study_values:
example_instance = example(var_under_study = value)
# I have to specify the var_under_study manually in this line.
# If it is var1, I have to manually type var1 here.
# I want to know if there is a way so that once I specify
# the string var_under_study in the argument of the
# start_simulation function, this line takes that and sets the
# variable with that name to the specified value.
other stuff here
我通过写作在别处调用这个函数
start_simulation(var_under_study = 'var1', var_under_study_values = [5, 15, 20])
现在,如果我想研究var2 的效果,我必须在 start_simulation 函数的参数中指定它:
start_simulation(var_under_study = 'var2', var_under_study_values = [5, 15, 20])
但我还必须返回定义函数的位置并更改example_instance = example(var_under_study = value) 行中的参数。例如,代替example_instance = example(var1 = value),我必须写:
example_instance = example(var2 = value)
有没有办法只在
中指定变量start_simulation(var_under_study = 'var2', var_under_study_values = [5, 15, 20])
并且拥有
example_instance = example(var1 = value)
考虑到这一点。
感谢您的帮助。如果我能澄清,请告诉我。我试图避免在多个地方更改相同/相似的东西,以免我因为忘记在某处更改而得到不正确的结果。
【问题讨论】: