Sub topic 1
How Python maps syntax to special methods
Prerequisites
This chapter assumes you can define a class with __init__ and regular methods. You should also know the basic built-in types (list, dict, tuple) and how for loops and with statements work.
The core idea
Python syntax and many built-in functions are shortcuts for method calls. When you write a + b, Python calls a method named __add__. When you write len(x), it calls x.__len__(). These methods have double underscores on each side, so they are called dunder methods, or special methods. The set of hooks they form is the Python data model.
You almost never call a dunder method yourself. You define it on a class, and Python calls it when matching syntax appears.
| You write | Python calls |
|---|---|
| `repr(x)` | `type(x).__repr__(x)` |
| `x == y` | `type(x).__eq__(x, y)` |
| `x + y` | `type(x).__add__(x, y)` |
| `len(x)` | `type(x).__len__(x)` |
| `x[i]` | `type(x).__getitem__(x, i)` |
| `for item in x` | `type(x).__iter__(x)` |
| `with x:` | `type(x).__enter__(x)` and `__exit__` |
| `x(...)` | `type(x).__call__(x, ...)` |
A first example
The class below defines two special methods. The built-ins len() and abs() then work on its instances.
import math
class Arrow:
def __init__(self, dx, dy):
self.dx = dx
self.dy = dy
def __len__(self):
return 2
def __abs__(self):
return math.hypot(self.dx, self.dy)
a = Arrow(3, 4)
print(len(a)) # 2
print(abs(a)) # 5.0len(a) does not look for a method called len. It asks the type of a for __len__.
Lookup happens on the type
Python finds special methods on the class of an object, not on the instance. This matters when you try to add a hook to a single object.
class Box:
pass
b = Box()
b.__len__ = lambda: 5
try:
len(b)
except TypeError as e:
print(e) # object of type 'Box' has no len()The lambda sits in the instance dictionary, and len() ignores it. To make this work, define __len__ in the class body.
Because the lookup uses the type, subclasses inherit special methods like any other method. A subclass can also override them.
What happens when a method is missing
If the type lacks the needed method, Python raises TypeError. For example, Arrow(1, 2) + Arrow(3, 4) fails because Arrow has no __add__. The error message names the unsupported operand types.
Many dunder methods have a default from object. Every class gets __repr__, __eq__ (identity comparison), and __hash__ without you writing them. You override these defaults only when you need different behavior.
Why this design is useful
Your classes can then work with existing tools. A class with __len__ and __getitem__ works with list(), sorted(), and for loops without extra code. The rest of this tutorial goes through the groups of special methods in turn: representation, comparison, arithmetic, containers, iteration, and context managers.
Exercise
A class defines __len__ by assigning it to a single instance (obj.__len__ = lambda: 3) instead of in the class body. Why does len(obj) raise TypeError?
Show answer
Python looks up special methods on the type of the object, not in the instance's own dictionary. Since the class has no __len__, len(obj) fails. Defining __len__ inside the class body fixes it.
Exercise
Which special method does Python call for abs(a), and which for a[2]?
Show answer
abs(a) calls type(a).__abs__(a), and a[2] calls type(a).__getitem__(a, 2).