简体   繁体   中英

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

使用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

FYI - you can generate a dict from the members of an entire object using vars() :

class A:
    pass
A.foo = 10
A.bar = 'hello'

a = A()
b = vars(a)
print(b['bar'])  # prints hello

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM