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

标签 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)

请考虑这一点。

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

最佳答案

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

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

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

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

关于python - 将值赋给与 Python 中变量名相同的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4846509/

相关文章:

Python - 使用类 'get' 方法时如何返回不同的值?

python - 单例数据库连接

python - 字符串索引必须是整数而不是 str 字典

algorithm - 关于字符串、dp、图形或其他算法的问题

ruby - Ruby 中用字母表中的字符替换字符串的方法 + 索引 13

python - 使用变量创建目录问题

python - 将 XML 文件中的所有 <img> 标签替换为一个单词

python - 如何在曲面图上投影一条线?

ios - 如何在 Swift 5 中检查字符串是否以字母开头?

java - 如何将字符串变量值转换为变量名