Dunder methods and operator overloading
How len(), [], + and < find their way to methods you write yourself.
- Give a class readable str and repr representations
- Make an object behave like a container with __len__, __getitem__ and __setitem__
- Overload arithmetic and comparison operators
Python’s syntax is a thin layer over method calls. len(x) calls x.__len__(), x[2] calls x.__getitem__(2), and a + b calls a.__add__(b). These “double underscore” or dunder methods let your own classes plug into the language.
Printing an object
c_dunder_methods.py defines both representations:
def __str__(self): return f"MyClass with value:{self.value}"
def __repr__(self): return f"Myclass({self.value})"
print(obj) uses __str__, meant for people; repr(obj) and the interactive prompt use __repr__, meant for developers. A good __repr__ looks like the code that would recreate the object. If only one is defined, define __repr__: str() falls back to it, but not the other way round.
Behaving like a container
class MyList:
def __len__(self): return len(self.items)
def __getitem__(self, index): return self.items[index]
def __setitem__(self, index, v): self.items[index] = v
With these three, len(obj2) is 4, obj2[2] is 3, and after obj2[2] = 42 it is 42. A bonus: a class with __getitem__ that accepts 0, 1, 2, … can already be looped over — Python falls back to indexing until IndexError.
Operators
01add.py gives a Point an __add__:
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
print(Point(1, 2) + Point(2, 3)) # (3,5)
and 02lessthan.py makes Person objects comparable by age with __lt__, so p1 < p2 is True for ages 20 and 30. Two refinements worth knowing:
- Defining only
__lt__does not give you<=or>. Add the rest, or decorate the class withfunctools.total_orderingand define__eq__plus one ordering method. - If
__add__cannot handle the other operand, it shouldreturn NotImplementedrather than raise. Python then tries the other side’s__radd__, which is how2 * vectorcan work as well asvector * 2.
Try it yourself. Give Point a __repr__, an __eq__ and a __mul__ for scaling by a number, then make 3 * Point(1, 2) work too with __rmul__. Sort a list of Person objects with sorted() — which dunder does it need?