Code Explanation:
๐น 1. Defining the Descriptor Class
class D:
Creates a class D
This class will act as a descriptor
๐น 2. Implementing __get__
def __get__(self, obj, objtype):
return 99
__get__ makes D a descriptor
It controls how an attribute is read
Always returns 99
Parameters:
self → descriptor object
obj → instance accessing the attribute (a)
objtype → owner class (A)
๐ Important:
This descriptor defines only __get__, so it is a non-data descriptor.
๐น 3. Defining Class A
class A:
Creates a normal class A
๐น 4. Assigning Descriptor to Class Attribute
x = D()
x is a class attribute
Value is an instance of D
Since D has __get__, x is managed by the descriptor
๐น 5. Creating an Instance of A
a = A()
Creates object a
At this moment:
a.__dict__ is empty
x exists only in the class
๐น 6. Assigning to a.x
a.x = 5
What happens internally:
Python does NOT call the descriptor
Because D has no __set__
Python creates an instance attribute
a.__dict__['x'] = 5
๐ This overrides the descriptor for this instance.
๐น 7. Accessing a.x
print(a.x)
Attribute lookup order:
Instance dictionary (a.__dict__) → ✅ finds x = 5
Descriptor is skipped
Returned value is 5
✅ Final Output
5

0 Comments:
Post a Comment