【问题标题】:Assign value to a string that is the same as a variable name in Python为与 Python 中的变量名相同的字符串赋值
【发布时间】: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)

考虑到这一点。

感谢您的帮助。如果我能澄清,请告诉我。我试图避免在多个地方更改相同/相似的东西,以免我因为忘记在某处更改而得到不正确的结果。

【问题讨论】:

    标签: python string variables


    【解决方案1】:

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

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

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

    旁注:您应该以大写字母开头类名,以使它们与函数更容易区分。

    【讨论】:

    • 太棒了!效果很好。谢谢,菲利克斯。
    猜你喜欢
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    • 2017-01-02
    • 1970-01-01
    • 2023-03-18
    • 2016-06-04
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多