Python Forum
problem descriptors in Python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
problem descriptors in Python
#6
(Dec-26-2023, 04:15 PM)Gribouillis Wrote:
(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 class Thing. When we call vars(Thing)['spam'], we get the MyDescriptor instance that is stored in class Thing.
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'])
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>
The magic of the __get__() method is that the expression Thing.spam evaluates to the return value of the descriptor's __get__() method called with 3 arguments: the descriptor itself, None and the Thing class.

When thing is an instance of Thing, the expression thing.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.
hi
can I ask you what is the __main__ that appears in all output in running above code?
Reply


Messages In This Thread
problem descriptors in Python - by akbarza - Dec-26-2023, 11:13 AM
RE: problem descriptors in Python - by deanhystad - Dec-26-2023, 03:43 PM
RE: problem descriptors in Python - by akbarza - Dec-27-2023, 06:44 AM
RE: problem descriptors in Python - by akbarza - Dec-27-2023, 07:03 AM
RE: problem descriptors in Python - by Gribouillis - Dec-26-2023, 04:15 PM
RE: problem descriptors in Python - by akbarza - Dec-27-2023, 07:20 AM
RE: problem descriptors in Python - by Gribouillis - Dec-27-2023, 07:56 AM
RE: problem descriptors in Python - by akbarza - Dec-27-2023, 01:22 PM
RE: problem descriptors in Python - by deanhystad - Dec-27-2023, 09:01 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  does open() still take file descriptors in py3 Skaperen 2 3,419 Jan-25-2017, 02:30 AM
Last Post: Skaperen
  file descriptors Skaperen 7 6,717 Jan-15-2017, 09:18 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020