'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?



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tom Aarsen