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)