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, but it doesn't really answer the question All answers refer the second question in the post.
The Python documentation specifys:
Instance Binding
If binding to an object instance, a.x is transformed
into the call:
type(a).__dict__['x'].__get__(a, type(a))
.
But:
The first part of the (my code equivalent) statement type(t).__dict__["instance_att"]
, raises an KeyError as type(t).__dict__
does not have such an attribute. It is an instance level att. Isn't it?
What am I missing?