Code Explanation:
1. Defining the Descriptor Class
class Desc:
A class named Desc is created.
This class will act as a descriptor, meaning it controls access to an attribute.
2. Implementing the __get__ Method
def __get__(self, obj, owner):
return 99
__get__ is a special method used by descriptors.
It is called automatically whenever the attribute it controls is read/accessed.
Parameters:
self → the descriptor object
obj → the instance accessing the attribute (e.g., d)
owner → the class of the instance (e.g., Demo)
The method simply returns 99, regardless of object or class.
3. Defining a Class that Uses the Descriptor
class Demo:
x = Desc()
A class named Demo is defined.
The class attribute x is assigned an instance of Desc.
This makes x a managed attribute controlled by the descriptor.
Any access to x will go through Desc.__get__.
4. Creating an Instance of Demo
d = Demo()
An object d of class Demo is created.
It does not store a normal value for x; access is handled by the descriptor.
5. Accessing the Descriptor Attribute
print(d.x)
Here’s what Python does internally:
It sees d.x.
It finds that x is a descriptor.
It calls:
Desc.__get__(<Desc instance>, d, Demo)
__get__ returns 99.
print prints that value.
6. Final Output
99


0 Comments:
Post a Comment