April 2019
Intermediate to advanced
646 pages
16h 48m
English
Special methods (https://docs.python.org/3/reference/datamodel.html#special-method-names) start and end with a double underscore and form so-called protocols of the language (see Chapter 4, Modern Syntax Elements - Above the Class Level). Some developers used to call them dunder methods as a portmanteau of double underscore. They are used for operator overloading, container definitions, and so on. For the sake of readability, they should be gathered at the beginning of class definitions, as shown in the following code:
class WeirdInt(int): def __add__(self, other): return int.__add__(self, other) + 1 def __repr__(self): return '<weirdo %d>' % self # public API def do_this(self): print('this') def do_that(self): print('that') ...