1

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?

LIFE1UP
  • 47
  • 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
  • 915
  • 1
  • 19