Code Explanation:
1. Defining Class D
class D:
Explanation:
This line creates a class named D.
This class will act as a descriptor.
A descriptor is a class that defines special methods like __get__, __set__, or __delete__ to control attribute access.
2. Defining the __get__ Method
def __get__(self, obj, objtype):
Explanation:
__get__ is a descriptor method.
It is automatically called when the attribute is accessed (read).
Parameters:
self → descriptor object (D)
obj → instance of class A
objtype → the class (A)
When we access a.x, Python internally calls:
D.__get__(descriptor, a, A)
3. Returning a Value
return 50
Explanation:
Whenever x is accessed through an object, this method returns 50.
So the descriptor controls the value returned.
Meaning:
a.x → 50
4. Defining Class A
class A:
Explanation:
This creates another class named A.
5. Creating Descriptor Attribute
x = D()
Explanation:
Here an object of class D is assigned to attribute x.
This makes x a descriptor attribute.
Accessing x will trigger the __get__ method.
So:
A.x → descriptor object of class D
6. Creating an Object
a = A()
Explanation:
This creates an instance a of class A.
7. Adding Attribute Directly to Object Dictionary
a.__dict__['x'] = 20
Explanation:
__dict__ stores all instance attributes of an object.
This line manually adds an attribute:
x = 20
inside the object's dictionary.
So internally:
a.__dict__ = {'x': 20}
8. Printing a.x
print(a.x)
Explanation:
Python checks attributes in this order:
Data descriptor (__get__ + __set__)
Instance dictionary
Non-data descriptor (__get__ only)
Class attributes
Here:
D defines only __get__, so it is a non-data descriptor.
Python first checks instance dictionary.
It finds:
a.__dict__['x'] = 20
So Python returns 20 instead of calling the descriptor.
9. Final Output
20

0 Comments:
Post a Comment