在__init__中创建类中的属性

时间:2011-08-15 12:49:22

标签: 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__, '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放到元类

1 个答案:

答案 0 :(得分:2)

您确实不应该允许实例在其类中放置属性。 如果你有很多实例会怎么样?每个实例都会覆盖以前的属性定义。 (的确,这就是你发布的输出中有5个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
相关问题