Skip to content Skip to sidebar Skip to footer

Behaviour Of Descriptor Concept In Python (confusing)

I understood python descriptor but I have a little confusion about this.. if you have a class descriptor as follows class Descriptor(object): def __get__(self, instance, owner)

Solution 1:

In Test1 your Descriptor isn't really used as a descriptor, it's just a normal attribute called name, that happens to have some the special methods. But that doensn't really make it a descriptor yet.

If you read the docs about how descriptors are invoked, youll see the mechanism that is used to invoke the descriptors methods. In your case this would mean t.name woud be roughly equivalent to:

type(t).__dict__['name'].__get__(t, type(t))

and t1.name:

type(t1).__dict__['name'].__get__(t1, type(t1))

name is looked up in the __dict__ of the class, not of the instance, so that's where the difference is, Test1.__dict__ doesn't have a descriptor called name:

>>> Test.__dict__['name']
<__main__.Descriptor object at 0x7f637a57bc90>
>>> Test1.__dict__['name']
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
KeyError: 'name'

What you also should consider, is that your descriptor sets the value attribute on itself, that means all instances of Test will share the same value:

>>>t1 = Test(1)
init test
setting
>>>t2 = Test(2)
init test
setting
>>>t1.name
getting
2
>>>t2.name
getting
2
>>>t1.name = 0
setting
>>>t2.name
getting
0

I think that what yo acutally want to do is to set value on instance instead of self, that would get you the expected behaviour in Test.

Post a Comment for "Behaviour Of Descriptor Concept In Python (confusing)"