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
Use setattr
:
setattr(A, 'foo', 10)
Yes! This can be done with a combination of getattr and setattr.
setattr(A, 'foo', 10)
getattr(A, 'foo') // Returns 10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With