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

Arup Rakshit ar at zeit.io
Mon Apr 29 15:17:02 EDT 2019


On 29/04/19 11:40 PM, Steven D'Aprano wrote:
> On Mon, Apr 29, 2019 at 11:25:51PM +0530, Arup Rakshit wrote:
>
>> Now I am not getting how the __set__() method from NonBlank is being
>> called inside the __init__() method. Looks like some magic is going on
>> under the hood. Can anyone please explain this how self.name and
>> self.email assignment is called the __set__ from NonBlank? What is the
>> name of this concept?
>
> I haven't read your code in detail, but it sounds like the Descriptor
> protocol. Descriptors are used "under the hood" by Python to implement
> methods, classmethod, staticmethod and property, among others, and are
> considered an advanced technique (only slightly less advanced than
> metaclasses).
>
> https://docs.python.org/3/howto/descriptor.html
>
> If you are *not* intentionally trying to write a custom descriptor, you
> should not use a __set__ method. (Perhaps you meant __setitem__?)
>
> In general, you should treat all dunder (Double UNDERscore) methods as
> private to Python, and only implement those that you need. Don't use
> them for your own purposes.
>
>
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.

-- 
Thanks,

Arup Rakshit



More information about the Tutor mailing list