typestar

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

  1. __len__ powers len() on the object.
  2. __getitem__ enables indexing with [].
  3. __contains__ answers the in operator.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 5 in Protocols & context managers, step 17 of 53 in Pythonic Python.

← Previous Next →