开发者

Assign value to a string that is the same as a variable name in Python

Suppose I have,

class example(object)
    def __init__(var1 = 10, var2 = 15, var3 = 5)
        do a few things here 

    Other methods here

There are other classes which are not relevant for the question.

To study the behavior of the system, I vary the inputs in the __init__ method above, one at a time. I have another function start_simulation function that takes the name of the input that I want to change as a string and its possible values. (It uses this name and the values to also create file names that store the results from the execution). For example, I have

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

I call this function elsewhere by writing

start_simulation(var_under_study = 'var1', var_under_study_values = [5, 15, 20])

Now, if I want to study effects of var2 instead, I have to specify it in the arguments of start_simulation function:

start_simulation(var_under_study = 'var2', var_under_study_values = [5, 15, 20])

but I also have to go back where the function is defined and change the argument in the line example_instance = example(var_under_开发者_如何学编程study = value). For instance, in place of example_instance = example(var1 = value) I have to write:

example_instance = example(var2 = value)

Is there a way I can just specify the variable in the

start_simulation(var_under_study = 'var2', var_under_study_values = [5, 15, 20])

and have

example_instance = example(var1 = value)

line take account of that.

Thanks for your help. Please let me know if I can clarify. I am trying to avoid having to change the same/similar thing in multiple places so that I don't get incorrect results because I forgot to change it somewhere.


If I understand you correctly, you want to specify the name of the parameter that should be set dynamically. You can use dictionary unpacking:

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

This will pass the contents of the dictionary as parameters to the function, where the keys are the parameter names and the values the values :)

Side note: You should start class names with an uppercase letter to make them more distinguishable from a function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜