Refer a String for Creating Class Dynamically

Question:

I want to use a string as class member name. the way I thought (but it doesn’t work) is in the below.

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

CONST = Constant()
CONST.add_Constant(name='EULER', value=2.718)
print(CONST.EULER)
Asked By: LIFE1UP

||

Answers:

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
Answered By: Tom Aarsen