【发布时间】:2011-10-27 06:20:18
【问题描述】:
如何在 init 中为类创建属性? 如果我使用此代码:
In [1]: import functools
In [2]: def test(id, wrap):
...: return id*2
In [3]: class A(object):
...: def __init__(self, id):
...: self.id = id
...: setattr(self.__class__, 'testing', property(functools.partial(test, self.id)))
In [4]: cl = []
In [5]: for i in range(5):
...: cl.append(A(i))
...:
In [6]: for b in cl:
...: print b.testing
我明白了:
8
8
8
8
8
我明白为什么会这样(因为属性是为类安装,而不是例如)。但我不明白如何向实例添加属性?如果在 setattr 中使用 self,我得到:
<property object at 0x1018def70>
<property object at 0x1018e9050>
<property object at 0x1018e9100>
<property object at 0x1018e91b0>
<property object at 0x1018e9260>
我看过这个话题:create class properties,但不明白,如何将 id 放入元类
【问题讨论】:
标签: python class properties metaclass