1

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)
LIFE1UP
  • 39
  • 6
  • Welcome to Stack Overflow. I linked some duplicates that explain the standard tools for addressing your question in Python. But - why not [just use a dictionary](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables)? Or an [enum with custom values](https://docs.python.org/3/library/enum.html#planet), depending on the actual *problem you are trying to solve* with the `Constant` class? – Karl Knechtel Jan 19 '22 at 10:39

1 Answers1

2

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
Tom Aarsen
  • 1,170
  • 2
  • 20