Code Explanation:
1. Defining the Descriptor Class
class D:
Creates a class D
This class is intended to be a descriptor
๐น 2. Implementing the __get__ Method
def __get__(self, obj, objtype):
return 100
__get__ makes D a descriptor
It is automatically called when the attribute is accessed
Parameters:
self → the descriptor object (D instance)
obj → the instance accessing the attribute (A()), or None if accessed via class
objtype → the owner class (A)
๐ This method always returns 100
๐น 3. Defining Class A
class A:
Creates a normal class A
๐น 4. Assigning the Descriptor to a Class Attribute
x = D()
x becomes a class attribute
Its value is an instance of D
Since D implements __get__, x is now a descriptor-managed attribute
๐น 5. Creating an Object of Class A
A()
Creates an instance of class A
No __init__ method is defined, so nothing else runs
๐น 6. Accessing the Descriptor Attribute
print(A().x)
What happens internally:
Python sees attribute access .x
Finds x in class A
Sees that x has a __get__ method
Calls:
D.__get__(x_descriptor, obj=A(), objtype=A)
__get__ returns 100
✅ Final Output
100

0 Comments:
Post a Comment