python, how to convert string to class member name? [duplicate]

I want to convert string to class member name.

my question looks like this:

class Constant():
    def add_Constant(self, name, value):
        self.locals()[name] = value  # <- this doesn't work!
    # def
# class

to do this:

CONST = Constant()
CONST.add_Constant(name='EULER', value=2.718)
print(CONST.EULER)

But above code doesn't work. Is there any way to add class members based on strings?


You can use setattr:

class Constant():
    def add_Constant(self, name, value):
        setattr(self, name, value) # <- this does work!

CONST = Constant()
CONST.add_Constant(name='EULER', value=2.718)
print(CONST.EULER)

This outputs:

2.718