Line-by-Line Explanation
class Descriptor:
This defines a custom descriptor class. In Python, a descriptor is any object that implements at least one of the following methods:
__get__()
__set__()
__delete__()
Descriptors are typically used for custom attribute access logic.
def __get__(self, obj, objtype=None):
This defines the getter behavior for the descriptor.
self: the descriptor instance
obj: the instance of the class where the descriptor is accessed (e.g., MyClass() object)
objtype: the class type (usually not used unless needed)
return 42
Whenever the attribute is accessed, this method returns the constant 42.
class MyClass:
A normal class where you're going to use the descriptor.
attr = Descriptor()
Here:
attr becomes a descriptor-managed attribute.
It's now an instance of Descriptor, so any access to MyClass().attr will trigger the __get__() method from Descriptor.
print(MyClass().attr)
Let’s unpack this:
MyClass() creates an instance of MyClass.
.attr is accessed on that instance.
Since attr is a descriptor, Python automatically calls:
Descriptor.__get__(self=attr, obj=MyClass(), objtype=MyClass)
And we know __get__() always returns 42.
Output:
42
0 Comments:
Post a Comment