[Tutor] self.name is calling the __set__ method of another class

Steven D'Aprano steve at pearwood.info
Mon Apr 29 19:41:44 EDT 2019


On Tue, Apr 30, 2019 at 12:47:02AM +0530, Arup Rakshit wrote:

> I really didn't write that code by myself. The day I'll you will not see 
> me here everyday :) . I was watching a PyCon video 
> https://youtu.be/81S01c9zytE?t=8172 where the author used this code. But 
> his explanation is not clear to me. The main problem is that the guy who 
> was recorded it far away from the projector, so what speaker were 
> showing there is not clear. So thought to ask here as usual. Because I 
> felt so lost with this trick.

Okay, the short, SIMPLIFIED (and therefore inaccurate) summary of 
descriptors:

Descriptors are the "magic" used by Python whenever it does an attribute 
lookup. When you do any sort of attribute lookup or assignment:

    x = spam.eggs

    spam.eggs = value

Python looks at spam and spam's class for an attribute called "eggs", 
and if that attribute is an object with a __set__ or __get__ method, it 
calls that method:

    x = spam.eggs
    => x = spam.eggs.__get__()

    spam.eggs = value
    => spam.eggs.__set__(value)

For the gory details of what *precisely* happens, see the Howto Guide:

https://docs.python.org/3/howto/descriptor.html


Python has a few common descriptors built in:

- ordinary methods
- classmethod
- staticmethod
- property

Apart from staticmethod, they're all pretty common in code. But writing 
your own custom descriptors is fairly rare. I've only done it once, in 
25+ years of using Python.


-- 
Steven


More information about the Tutor mailing list