Code Explanation:
1. ๐️ Create the Descriptor Class
class D:
A class D is created.
This class will act as a descriptor because it defines the special method __get__().
2. ๐ Define __get__()
def __get__(self, obj, owner):
__get__() controls what happens when the descriptor attribute is read.
Here:
- obj → the instance accessing the attribute
- owner → the class that owns the descriptor
For a.x:
obj → a
owner → A
3. ๐ฏ Return 50
return 50
Whenever the descriptor's value is retrieved, it returns:
50
So the descriptor does not return the value stored in the instance dictionary.
4. ๐ Put Descriptor in Class A
class A: x = D()
Here:
A.x → D object
The object created by D() is assigned to A.x.
Because D defines __get__(), x becomes a descriptor.
5. ๐ Create Object a
a = A()
An instance of A is created.
At this point, a doesn't have an "x" entry in its own __dict__.
6. ๐ Manually Add x to a.__dict__
a.__dict__["x"] = 100
Now the instance dictionary contains:
a.__dict__
which is approximately:
{'x': 100}
So it may look like:
a.x
should return 100.
But there is an important descriptor rule.
7. ⚡ Access a.x
print(a.x)
Python sees that A.x is a non-data descriptor because D has __get__() but does not have __set__() or __delete__().
Normally, an instance attribute can override a non-data descriptor.
So in fact, this code:
a.__dict__["x"] = 100
means the instance value wins.
Therefore:
a.x → 100
✅ Correct Final Output
100

0 Comments:
Post a Comment