pri*_*ing 14 python class setattr
我想做这样的事情:
property = 'name'
value = Thing()
class A:
setattr(A, property, value)
other_thing = 'normal attribute'
def __init__(self, etc)
#etc..........
Run Code Online (Sandbox Code Playgroud)
但我似乎无法找到对类的引用,以便setattr像在类定义中分配变量一样工作.我怎样才能做到这一点?
Vit*_*dov 17
你可以做得更简单:
class A():
vars()['key'] = 'value'
Run Code Online (Sandbox Code Playgroud)
与之前的答案相反,此解决方案可以很好地与外部元类(例如,Django模型)配合使用.
Ign*_*ams 14
您需要使用元类来实现此目的:
property = 'foo'
value = 'bar'
class MC(type):
def __init__(cls, name, bases, dict):
setattr(cls, property, value)
super(MC, cls).__init__(name, bases, dict)
class C(object):
__metaclass__ = MC
print C.foo
Run Code Online (Sandbox Code Playgroud)
这可能是因为A当你去setattr(A, p, v)那里时,课程没有完全初始化.
要尝试的第一件事就是在关闭class块之后将setupattr向下移动,看看是否有效,例如
class A(object):
pass
setattr(A, property, value)
否则,伊格纳西奥刚刚说过关于元类的事情.