我正试图在类似于以下的代码中摆脱 exec
:
class A(object):
for field in ['one', 'two', 'three']:
exec '%s = "%s value"' % (field, field)
...这样:
>>> A.one
'one value'
>>> A.two
'two value'
>>> A.three
'three value'
编辑:并且还满足主题中提到的要求,即 A.one
是 'one value'
,在 A
被实例化之前(不要误认为 A()
已实例化)。
有办法吗?
最佳答案
>>> values = 'one', 'two', 'three'
>>> A = type('A', (object,), {i: i + ' value' for i in values})
>>> A.one
'one value'
>>> A.three
'three value'
关于python - 在元类机制之前创建动态类字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3423361/