A class Python does not understand
The topic Classes and objects gave our own types attributes, methods and inheritance, and a dataclass gave Config a readable printout and comparison by value without a line of our code. A plain class gets neither. Here is a vector of numbers written as a plain class:
class Vector:
def __init__(self, *components):
self.components = tuple(float(x) for x in components)It holds the right data, and the language still treats it as a stranger. The address after 0x changes from run to run.
>>> v = Vector(3, 4)
>>> v
<__main__.Vector object at 0x...>
>>> v == Vector(3, 4)
False
>>> len(v)
Traceback (most recent call last):
...
TypeError: object of type 'Vector' has no len()
>>> v + v
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for +: 'Vector' and 'Vector'
>>> for x in v: pass
...
Traceback (most recent call last):
...
TypeError: 'Vector' object is not iterableBuilt-in types do all of this, and not because the interpreter treats them specially. Every piece of syntax that works on objects is defined as a call of a method with a double-underscore name, a special method (a "dunder" method), on the object's type:
| You write | Python calls |
|---|---|
repr(x), str(x), print(x) |
__repr__, __str__ |
x == y, hash(x) |
__eq__, __hash__ |
len(x), x[i], for, y in x, if x: |
__len__, __getitem__, __iter__, __contains__, __bool__ |
x + y, x * y, x @ y, -x, abs(x) |
__add__, __mul__, __matmul__, __neg__, __abs__ |
x(...), with x: |
__call__, __enter__ and __exit__ |
These methods and the rules for calling them make up the data model. A class that defines them speaks the language's own vocabulary, and so does every function built on it: print, sum, sorted, zip. This topic teaches Vector that vocabulary one group at a time.
"On the type" is meant literally. len(x) is type(x).__len__(x), and an instance attribute with the same name is ignored:
class Box:
def __len__(self):
return 3>>> b = Box()
>>> b.__len__ = lambda: 99
>>> len(b), b.__len__()
(3, 99)b.__len__() is an ordinary attribute lookup, and it finds the instance attribute first. len(b) goes straight to the type. CPython keeps a pointer to each special method in the type's C structure: one pointer instead of a dictionary search, and every instance of a type behaves the same. So write len(v), never v.__len__(). The built-in also checks the result, and for operators it runs the full protocol that a direct call skips.