Lesson 4 of 10
A class that acts like a list
- 14 min
- 6 checks
- 3 hints
- Go to task
Goal
len, in and for on your own class
Explanation
len(x), x[0], "a" in x and for s in x aren't special to lists. Each one calls a special method on the class: __len__, __getitem__, __contains__ and __iter__, in that order. Define them in your class and Python treats it just like a list.
The payoff is that people using your class don't have to learn new methods like get_song(0) and count(), and they get everything built on these methods for free, such as sorted, list and enumerate. An empty playlist even counts as False in if playlist:, just like a regular list.
The trap in __iter__ is that it must return a fresh iterator on every call. Make the class its own iterator and the second loop comes up empty, because the first one used it up. The simplest fix is to leave this to the inner list, which hands out a new iterator whenever it's asked.
Your task
Add all four methods to Playlist, building on self.songs, so the class works with len, indexing by position, in and for.
Checks
6 checks- len counts the songs
- Indexing works from both ends
- The in operator searches the songs
- A for loop visits the songs in order
- Works in more than one loop
- An empty playlist is False in an if