__repr__, __len__, __iter__, __contains__ & __add__
Objects that feel built-in
Lesson 11 of 20 · 12 min · Module 3: Objects that behave
Python’s own types work with len(), for loops, in, and +. Your classes can too, by defining special methods whose names start and end with double underscores.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Implement common special methods
- Make objects print helpfully
- Return new objects from operators
The idea
__repr__ controls how an object prints in the console. __len__ powers len(obj), __iter__ powers for loops, __contains__ powers in, and __add__ powers +. Return NotImplemented from __add__ for types you do not support.
class Basket:
def __init__(self, items):
self.items = list(items)
def __len__(self):
return len(self.items)
def __iter__(self):
return iter(self.items)
print(len(Basket(["apple", "pear"])))
01Special methods connect to syntax
len(p) calls p.__len__(), for song in p calls p.__iter__(), and "x" in p calls p.__contains__("x"). Python looks these up on your class automatically.
02A good repr helps debugging
When a list of playlists prints as [Playlist('Road trip', 3 songs)] instead of [<__main__.Playlist object at 0x…>], bugs become far easier to spot.
class P:
def __repr__(self):
return "P(42)"
print([P()])[P(42)]03Operators should not mutate
a + b on built-in types returns a new object and leaves a and b alone. Follow the same rule, so users of your class are never surprised.
Your turn
Playlist(name, songs=None). Support len(), iteration over songs in order, case-insensitive in, and repr() as Playlist('Road trip', 3 songs) (use 1 song for one). a + b returns a new playlist named "A + B" with the songs of a, then the songs of b that are not already in it (case-insensitive).What the checks look for
- Supports len() and iteration in order
- in ignores letter case
- repr shows the name and song count
- + merges without duplicates and without changing the originals
- Copies the songs list it receives
Take this with you
Special methods make your objects work naturally with Python’s syntax.
Go a little further
Add __eq__ so two playlists with the same name and songs compare equal.