marco marco - 5 months ago 9
Python Question

how to pass the name of a variable as a variable

How can I set the variable I want to change as a function argument? I want to define only one function, and not set_a(value), set_b(value), set_c(value), ...

class MyVarClass:
def __init__(self):
self.a = 1
self.b = 2
self.c = 3

# this works, but I don't want to write n functions
def set_a(myvar_object, value):
myvar_object.a = value

# this is what I actually want:
def set_vars(myvar_object, var_name, value):
myvar_object.var_name = value

myvar = MyVarClass()
# I want to do the same as myvar.a = 4
set_a(myvar, 4) # works as intended, now myvar.a is 4
set_vars(myvar, a, 4) # error, a is not defined

Answer

What you usually do is to create a method to the class like this:

class MyVarClass:
    def __init__(self):
        self.a = 1
        self.b = 2
        self.c = 3

    def set_a(self, value):
        self.a = value

If, for some reason, can't do it like this and you only have the name of the attribute as string, then you can use setattr:

setattr(myvar_object, 'a', value)

But usually what you do is just this line:

myvar_object.a = 4
Comments