Use String as variable name inside __init__ method

Viewed 46

I want to use strings as variable names inside a init method of a function, however it does not seem to work so far. I tried the following:

class SomeClass:

    def __init__(self, car_brand="BMW", **kwargs):
    
    
        car_brand = 'Mercedes'
    
        # change car_brand variable with exec
        exec("identifier " + "= 'Audi'")
    
        # change car_brand variabel with local
        str = "car_brand"
        locals()[str] = 'Audi'
    
        self.car_brand = car_brand
    
sc = SomeClass(car_brand="BMW")
sc.car_brand

My output is "Mercedes" so apparently it is possible to simply overwrite the input argument however it is not possible to overwrite the variable with "Audi" using the string "car_brand" as variable name.

1 Answers

There are multiple ways to accomplish this.

# modifying the globals
globals()[name] = value
from operator import setitem
setitem(globals(), name, value)
# custom dicionary, like globals
custom_dict[name] = value

Perhaps you want to modify only the current instance's attributes?

setattr(self, name, value)
Related