【问题标题】:Create property in class in __init__在 __init__ 的类中创建属性
【发布时间】: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


    【解决方案1】:

    你真的不应该让一个实例在它的类中放置一个属性。 如果你有很多实例会发生什么?每个实例化都会覆盖属性的先前定义。 (事实上​​,这就是为什么您在发布的输出中有五个 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
    

    【讨论】:

    • 我正在考虑这种方法并尝试这样做topic
    猜你喜欢
    • 2016-11-10
    • 1970-01-01
    • 2011-01-30
    • 2011-04-05
    • 1970-01-01
    • 2015-12-08
    • 2011-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多