L4·OOP & Errors

Dunder Methods

__methods__ that hook into Python's syntax.

dunder__str____eq____len__

§ 1The Big Ones

__init__, __repr__, __str__, __eq__, __hash__, __len__, __getitem__, __iter__, __call__, __enter__/__exit__.

§ 2Operator overloading

__add__, __mul__, __lt__ etc. — a + b calls a.__add__(b) or b.__radd__(a).

Example

1class Vector:
2 def __init__(self, x, y):
3 self.x, self.y = x, y
4 def __add__(self, other):
5 return Vector(self.x+other.x, self.y+other.y)
6 def __repr__(self):
7 return f"Vector({self.x}, {self.y})"
8
9print(Vector(1,2) + Vector(3,4))

Try it live · Python runs in your browser

Loading playground…

Checkpoint quiz

Question 1 / 2
Which dunder makes len(obj) work?