__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)Step by step:
__len__(self)must return a whole number, 0 or more__getitem__(self, i)gets the index (or a slice like1:3) and returns the item; give it a bad index and the inner list raises IndexError, just like a list does__contains__(self, item)returns True or False- without
__contains__,instill 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 givesValueError: __len__() should return >= 0. - A bad index.
p[5]on a 1-item playlist raisesIndexError: list index out of rangefrom the list inside, which is what a list would do. - Forgetting to return. A
__getitem__with noreturngivesNonefor every index.
Quiz
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"])))Which dunder method does
"pen" in bagcall?- bag.__contains__("pen")
- bag.__len__()
- "pen".__contains__(bag)
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])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)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
Give
Playlista__len__(how many songs) and a__contains__(is a song in it).Give
Decka__getitem__, sodeck[0]gives the first card and aforloop goes through all the cards.Write a class
Password(text)whoselen()is the number of letters, and whosestr()is one*per letter, so printing never shows the real password.