Dec-27-2023, 07:20 AM
(Dec-26-2023, 04:15 PM)Gribouillis Wrote:hi(Dec-26-2023, 11:13 AM)akbarza Wrote: can you explain descriptors in Python?A descriptor is an object that has a__get__()
method and potentially also a__set__()
and a__del__()
method. This descriptor can be used as a member in another class to emulate a dynamic attribute.
In the below example, we create a MyDescriptor instance as the member 'spam' in the dictionary of classThing
. When we callvars(Thing)['spam']
, we get theMyDescriptor
instance that is stored in classThing
.
class MyDescriptor: def __get__(self, obj, objtype=None): return (self, obj, objtype) class Thing: spam = MyDescriptor() thing = Thing() print(thing.spam) print(Thing.spam) print(vars(Thing)['spam'])The magic of the
Output:(<__main__.MyDescriptor object at 0x7f4e7f157fd0>, <__main__.Thing object at 0x7f4e7f157eb0>, <class '__main__.Thing'>) (<__main__.MyDescriptor object at 0x7f4e7f157fd0>, None, <class '__main__.Thing'>) <__main__.MyDescriptor object at 0x7f4e7f157fd0>__get__()
method is that the expressionThing.spam
evaluates to the return value of the descriptor's__get__()
method called with 3 arguments: the descriptor itself, None and the Thing class.
Whenthing
is an instance ofThing
, the expressionthing.spam
evaluates to the return value of the descriptor's__get__()
method called with 3 arguments: the descriptor itself, the Thing instance thing and the Thing class.
In the above example, the__get__()
method returns its tuple of arguments, but it could return anything.
can I ask you what is the __main__ that appears in all output in running above code?