Container dunder methods in Python
Teaching a class to behave like a built-in container.
class Playlist:
def __init__(self, *songs):
self.songs = list(songs)
def __len__(self):
return len(self.songs)
def __getitem__(self, i):
return self.songs[i]
def __contains__(self, title):
return title in self.songs
mix = Playlist("Africa", "Take On Me", "Hey Ya")
count = len(mix)
opener = mix[0]
has_it = "Hey Ya" in mix
How it works
__len__powerslen()on the object.__getitem__enables indexing with[].__contains__answers theinoperator.
Keywords and builtins used here
Playlistclassdeflenlistreturnself
The run, in numbers
- Lines
- 18
- Characters to type
- 327
- Tokens
- 97
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 55 seconds.
Step 3 of 5 in Protocols & context managers, step 17 of 53 in Pythonic Python.