shiyon sufa shiyon sufa - 11 months ago 47
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') = ''

def __get__(self,instance,owner):

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


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. 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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download