Python 3D Academyবাংলা

__len__, __getitem__ and __contains__: objects that hold things

🌍 In real life. A music app's playlist answers three questions without you opening it up:

  • how many songs? (12 songs)
  • what's song number 3?
  • is this song in it?

Your own classes can answer the same questions with the same Python you use on lists: len(playlist), playlist[2] and "Hello" in playlist. Each one calls a dunder method:

  • len(x) → x.__len__()
  • x[i] → x.__getitem__(i)
  • item in x → x.__contains__(item)

The idea in one sentence: __len__, __getitem__ and __contains__ let your class answer len(x), x[i] and item in x, just like a list.

Its words:

  • container: an object that holds items, like a playlist
  • __len__: how many items, a whole number 0 or more
  • __getitem__: the item at an index (or a slice)
  • __contains__: is this item inside?

A password box is a good first example. len(p) tells a website whether the password is long enough, and printing it should never show the real letters, just stars:

class Playlist:
    def __init__(self, songs):
        self.songs = songs

    def __len__(self):
        return len(self.songs)

    def __getitem__(self, i):
        return self.songs[i]

    def __contains__(self, song):
        return song in self.songs

mix = Playlist(["Hello", "Yellow", "Halo"])
print(len(mix))
print(mix[0], mix[-1])
print("Yellow" in mix, "Rain" in mix)
for song in mix:          # __getitem__ makes for loops work too
    print("Playing", song)
Each method just passes the question on to the list inside: the playlist looks and feels like a list from the outside.

Step by step:

  1. __len__(self) must return a whole number, 0 or more
  2. __getitem__(self, i) gets the index (or a slice like 1:3) and returns the item; give it a bad index and the inner list raises IndexError, just like a list does
  3. __contains__(self, item) returns True or False
  4. without __contains__, in still works when there is a __getitem__: Python checks the items one by one

Why use the same names as lists? Code that already works with lists works with your class too: len, indexing, in, and even for loops (via __getitem__). Nobody has to learn a new set of method names for your playlist.

What it costs. These usually hand the job to a list inside, so they cost what the list's operations cost: len and indexing instantly, in item by item. A __contains__ backed by a set answers in almost instantly.

Mistakes and edge cases.

  • A negative length. __len__ returning -1 gives ValueError: __len__() should return >= 0.
  • A bad index. p[5] on a 1-item playlist raises IndexError: list index out of range from the list inside, which is what a list would do.
  • Forgetting to return. A __getitem__ with no return gives None for every index.

Quiz

  1. What does this print?

    class Bag:
        def __init__(self, items):
            self.items = items
    
        def __len__(self):
            return len(self.items)
    
    print(len(Bag(["pen", "book", "apple"])))
  2. Which dunder method does "pen" in bag call?

    • bag.__contains__("pen")
    • bag.__len__()
    • "pen".__contains__(bag)
  3. What does this print?

    class Row:
        def __init__(self, seats):
            self.seats = seats
    
        def __getitem__(self, i):
            return self.seats[i]
    
    r = Row(["A1", "A2", "A3"])
    print(r[1], r[-1])
    print([s for s in r])
  4. What does this print?

    class Team:
        def __init__(self, names):
            self.names = names
    
        def __contains__(self, name):
            return name.lower() in self.names
    
    t = Team(["ana", "bo"])
    print("ANA" in t, "cy" in t)
  5. Which line has a mistake?

    class Shelf:
        def __init__(self, books):
            self.books = books
    
        def __len__(self):
            return str(len(self.books))
    
    print(len(Shelf(["Dune"])))

Coding tasks

  1. Give Playlist a __len__ (how many songs) and a __contains__ (is a song in it).

  2. Give Deck a __getitem__, so deck[0] gives the first card and a for loop goes through all the cards.

  3. Write a class Password(text) whose len() is the number of letters, and whose str() is one * per letter, so printing never shows the real password.