开发者

Create property in class in __init__

开发者 https://www.devze.com 2023-03-28 08:30 出处:网络
How I\'m can create a property for class in init? If I\'m use this code: In [1]: import functools In [2]: def test(id, wrap):

How I'm can create a property for class in init? If I'm use this code:

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               
 开发者_StackOverflow  ...:         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

I'm get:

8
8
8
8
8

I'm understand why this (because property install for class, not for instance). But I'm not understand how add property to instance? If Use self in setattr, I'm get:

<property object at 0x1018def70>
<property object at 0x1018e9050>
<property object at 0x1018e9100>
<property object at 0x1018e91b0>
<property object at 0x1018e9260>

I'm read this topic: create class properties, but not understand, how put id to metaclass


You really shouldn't allow an instance to place a property in its class. What happens if you have many instances? Each instantiation overrides the previous definition of the property. (Indeed, that is why you got five 8's in the output you posted).

Better would be:

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)

which yields

0
2
4
6
8
0

精彩评论

暂无评论...
验证码 换一张
取 消