Python 在_init中的类中创建属性__
如何在init中为类创建属性? 如果我正在使用此代码:Python 在_init中的类中创建属性__,python,class,properties,metaclass,Python,Class,Properties,Metaclass,如何在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__,
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>
我读过这个主题:,但不明白,如何将id放入元类您真的不应该允许实例在其类中放置属性。 如果有很多实例,会发生什么?每个实例化都会覆盖以前的属性定义。(事实上,这就是为什么在你发布的输出中有五个8) 最好是:
class A(object):
@property
def testing(self):
return functools.partial(test, self.id)
def __init__(self, id):
self.id = id
for b in cl:
print b.testing(1)
产生
0
2
4
6
8
我正在考虑这个方法,并尝试这样做