I am trying to post this for hours. But it always prevented due to some code format issue:
your post appears to contain code that is not properly formatted as code
Please advise.
Why Python Descriptor Work for Class Level Attribute and not for an Instance Level Attribute.
class PropDescriptor:
def __init__(self,*args):
print("Init {} {}".format(type(self),args))
self.value = 0
def __get__ (self,instance,owner):
print("get using descriptor")
return instance.instance_att
def __set__(self, instance, value):
print("set using descriptor")
instance.instance_att = value
class TestClass:
class_att = PropDescriptor()
def __init__(self):
self.instance_att = PropDescriptor()
t = TestClass()
print("set instance level...")
t.instance_att = 3
print("\nget instance level...")
print(t.instance_att)
print("\nset class level...")
t.class_att = 4
print("\nget class level...")
print(t.class_att)
Output:
Init <class '__main__.PropDescriptor'> ()
Init <class '__main__.PropDescriptor'> ()
set instance level...
get instance level...
3
set class level...
set using descriptor
get class level...
get using descriptor
4
looks like the descriptor is not used for the instance_att
.
I found this identical question, however I did not understand the answer.
Also read this, but I don't understand.
It is also written here:
Instance Binding If binding to an object instance, a.x is transformed into the call:
type(a).__dict__['x'].__get__(a, type(a))
.
But:
type(t).__dict__["instance_att"]
, raises an KeyError as type(t).__dict__
does not have such an attribute. It is an instance level att.
What am I missing?