shiyon sufa shiyon sufa - 9 months ago 38
Python Question

"class" vs "instance of class" __get__ and __set__?

Q: why hh.a = 2 is not what I expect but b.a = 2 is Okay?

here's the code:

class D:
def __init__(self):
print('this is init')
self.name = ''

def __get__(self,instance,owner):
print('getting')
return self.name


def __set__(self,instance,value):
print('setting')
self.name = value
return self.name


and...

class hh:
a = D()

b = hh()


when i set hh.a = 2 it wont call the print('setting') but b.a = 2 is Okay. Can you explain this ?

Answer Source

Descriptor setters are only activated when setting the attribute on an instance of the class that owns the descriptor. They don't apply to the class itself or its subclasses. This is documented in the Python data model.

3.3.2.1. Implementing Descriptors

The following methods only apply when an instance of the class containing the method (a so-called descriptor class) appears in an owner class (the descriptor must be in either the owner’s class dictionary or in the class dictionary for one of its parents).