Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 873
Rubens Avatar asked Dec 26 '12 19:12

Rubens


2 Answers

Use setattr:

setattr(A, 'foo', 10)
like image 77
mVChr Avatar answered Nov 08 '22 22:11

mVChr


Yes! This can be done with a combination of getattr and setattr.

setattr(A, 'foo', 10)
getattr(A, 'foo') // Returns 10
like image 5
Foggzie Avatar answered Nov 08 '22 22:11

Foggzie