将值赋给与Python中的变量名称相同的字符串

时间:2011-01-31 00:08:14

标签: python string variables

假设我有,

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)

考虑到这一点。

感谢您的帮助。如果我能澄清,请告诉我。我试图避免在多个地方改变相同/类似的事情,这样我就不会得到不正确的结果,因为我忘了在某个地方改变它。

1 个答案:

答案 0 :(得分:3)

如果我理解正确,您需要指定应动态设置的参数的名称。您可以使用dictionary unpacking

example_instance = example(**{var_under_study: value})

这会将字典的内容作为参数传递给函数,其中键是参数名称,值是值:)

旁注:您应该使用大写字母启动类名,以使它们与函数更加明显。