使用字符串动态添加类成员来命名它

Rub*_*ens 4 python class dynamic member

在Python中,我非常清楚可以在定义之后将类添加到类中.但是,有没有办法使用字符串的内容命名成员?

例如,我可以这样做:

class A:
    pass
A.foo = 10

a = A()
print a.foo
Run Code Online (Sandbox Code Playgroud)

但是有一些方法可以做到这一点:

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

a = A()
print a.foo
Run Code Online (Sandbox Code Playgroud)

mVC*_*Chr 11

用途setattr:

setattr(A, 'foo', 10)
Run Code Online (Sandbox Code Playgroud)


Fog*_*zie 5

是! 可以结合使用getattrsetattr

setattr(A, 'foo', 10)
getattr(A, 'foo') // Returns 10
Run Code Online (Sandbox Code Playgroud)