Module 11 · Object-Oriented Programming — topic 24 of 25
Special methods
Dunder methods that integrate classes with Python's syntax: __str__ and __repr__, comparison (__eq__, __lt__), arithmetic (__add__, __mul__), and container protocols (__len__, __getitem__, __contains__, __iter__, __bool__).
Learning objectives
- Implement __str__ and __repr__
- Overload operators and comparisons
- Make a class behave like a container
Definition
Special methods (also called magic or dunder methods) have names with double underscores, such as __len__ and __add__. Python calls them automatically for built-in operations, letting your objects work with len(), +, ==, in, for loops and print.
Introduction
Why does len(my_list) work, and why can you write a + b for strings? Because list defines __len__ and str defines __add__. Your own classes can do the same.
Why it matters
Special methods make your classes feel built in. A Vector that supports + and a Playlist that supports len and in are easier to use than ones with custom method names.
Detailed explanation
__repr__ returns an unambiguous developer view (ideally valid Python like Point(2, 3)); __str__ returns a friendly view for print. If only __repr__ exists, print uses it.
Comparison: __eq__ powers ==; __lt__, __le__, __gt__ and __ge__ power the ordering operators and let sorted() work. functools.total_ordering can fill in the rest from __eq__ and __lt__.
Arithmetic: __add__, __sub__, __mul__ and friends implement +, -, *. Return NotImplemented for unsupported types so Python can try the other operand.
Containers: __len__ for len(), __getitem__ for indexing and slicing, __contains__ for in, __iter__ for loops, and __bool__ for truth testing.
__init__ itself is a special method; others include __call__ (make instances callable) and __enter__/__exit__ (with statements).
Defining __eq__ without __hash__ makes instances unhashable, so they can't be set members or dict keys unless you also define __hash__.
Syntax
- Python calls dunder methods for operators and built-ins.
- __repr__ for developers, __str__ for users.
- Return NotImplemented for unsupported types.
Code examples
__str__ and __repr__
(2, 3) Point(2, 3) [Point(2, 3), Point(0, 0)]
Operators and equality
Vector(4, 6) Vector(3, 6) True
More examples
A container-like class
Playlist('Focus', 3 songs) 3
Weightless Experience
True
['WEIGHTLESS', 'CLAIR DE LUNE']
FalseStep-by-step explanation
- __len__ and __getitem__ make len(pl) and pl[0] work, including negative indexes.
- __contains__ customises in to ignore case.
- __iter__ lets the playlist be used in for loops and comprehensions; __bool__ makes an empty playlist falsy.
Expected output
Running “A container-like class” prints exactly:
Practical applications
- pathlib uses __truediv__ so paths can be joined with /.
- Decimal and Fraction overload arithmetic operators.
Best practices
- Always define a useful __repr__.
- Implement only the special methods that make sense for the type.
- Keep operator meanings intuitive.
Common mistakes
Calling dunder methods directly
Avoid
Prefer
Use the operator or built-in; Python handles the protocol details.
Returning a string from __len__
Avoid
Prefer
__len__ must return a non-negative int, otherwise len() raises TypeError.
Important notes
- @dataclass generates __init__, __repr__ and __eq__ automatically.
Key takeaways
- Special methods connect classes to Python syntax.
- __repr__/__str__ control display; __eq__/__lt__ control comparison.
- __len__, __getitem__, __iter__, __contains__ make container-like classes.
Try it yourself
- 1Add __sub__ and __abs__ (length) to the Vector class.
- 2Make a Money class that supports +, == and < and refuses to add different currencies.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
2 questions test this exact topic. Answers and explanations are revealed after you submit.
- ModerateWhat is printed?
- ModerateWhat is printed?