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

Steven D'Aprano steve at pearwood.info
Mon Apr 29 14:10:39 EDT 2019


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.


-- 
Steven


More information about the Tutor mailing list