pythonclassdynamicmember

Dynamically add class member using string to name it


In Python, I'm quite aware of the fact that one may add members to classes after their definition. But, is there a way to name a member using the content of a string?

For example, I may do this:

class A:
    pass
A.foo = 10

a = A()
print a.foo

But is there some way to do this:

name = "foo"
class A:
    pass
A.[some trick here(name)] = 10

a = A()
print a.foo

Solution

  • Use setattr:

    setattr(A, 'foo', 10)