1

Say, we put two different descriptors in a class, and then check how they work being requested from an instance and a class itself.

class DescrGet:
    def __get__(self, instance, typ):
        print("DescrGet")

class DescrSet:
    def __set__(self, instance, value):
        print("DescrSet")

class A:
    descr_get = DescrGet()
    descr_set = DescrSet()
>>> a = A()
>>> a.descr_get
DescrGet
>>> a.descr_set = 42
DescrSet
>>> A.descr_get
DescrGet
>>> A.descr_set = 42
>>> print(A.descr_set)
42

Seems like quite inconsistent behaviour. From python docs page about descriptors, I get the basic concepts of how python looks up for requested attribute. But it says nothing about setting an atribute. Here, after searching in type(A).__dict__ (finds nothing of course) python continues to search in A.__dict__ for descriptor and when successfully finds it, calls __get__ method but (surprisingly) doesn't call __set__ and simply sets A.a to 42.

Could someone provide explanation for such behaviour or give any links?

A.King
  • 172
  • 2
  • 11

0 Answers0