要创建动态类变量,您似乎有两个选择 - 使用locals()
或__metaclass__
。我不喜欢分配给,locals()
但它似乎在类定义中起作用,并且比它的__metaclass__
替代方法更简洁。
这样使用靠谱locals()
吗?两种解决方案的优点/缺点是什么?
meta_attrs = ["alpha", "beta", "gamma"]
class C(object):
local_context = locals()
for attr in meta_attrs:
local_context[attr] = attr.upper()
class D(object):
class __metaclass__(type):
def __new__(mcs, name, bases, attrs):
for attr in meta_attrs:
attrs[attr] = attr.upper()
return type.__new__(mcs, name, bases, attrs)
if __name__ == '__main__':
print C.alpha, C.beta, C.gamma
print D.alpha, D.beta, D.gamma