A Playlist Container
Write a class Playlist(songs=None) that holds song names and behaves like a sequence:
add(song)appends a song.len(p)gives the number of songs;p[i]gives a song (negative indexes work);p[a:b]gives a list of songs.for song in ploops over the songs in order, and"x" in ptests membership.p + qgives a newPlaylistwith the songs of both; adding anything else raisesTypeError.- The list you pass in is copied: changing it later must not change the playlist.
Understand the problem
Match each behaviour to its special method.
Which special method does p[2] call?
__index____getitem____get__
p[key] calls p.__getitem__(key). The key can be an integer or a slice object (for p[1:3]), so the method must handle both.
A class defines only __len__ and __getitem__ (with integer indexes). Which of these then works without extra code?
for song in p- None of them
p + q
Python falls back to calling __getitem__(0), __getitem__(1), ... until IndexError, so a class with __getitem__ is already iterable, and in works the same way. It is the old iteration protocol; the modern way is __iter__.
Write the solution
Write the class.
class Playlist:
# Write your code here.
pass
Hint 1: a question to ask yourself
If the class keeps its songs in a list, which operations can simply be passed on to that list?
Hint 2: the shape of the answer
Store self._songs = list(songs or []) (this also copies). __len__, __getitem__ and __iter__ can return the list's own. __add__ checks the type and builds a new Playlist.
Reflect
Solution
class Playlist:
def __init__(self, songs=None):
self._songs = list(songs or [])
def add(self, song):
self._songs.append(song)
def __len__(self):
return len(self._songs)
def __getitem__(self, index):
return self._songs[index]
def __iter__(self):
return iter(self._songs)
def __contains__(self, song):
return song in self._songs
def __add__(self, other):
if not isinstance(other, Playlist):
return NotImplemented
return Playlist(self._songs + other._songs)
Another way: inherit from collections.abc.Sequence
from collections.abc import Sequence
class Playlist(Sequence):
def __init__(self, songs=None):
self._songs = list(songs or [])
def add(self, song):
self._songs.append(song)
def __len__(self):
return len(self._songs)
def __getitem__(self, index):
return self._songs[index]
def __add__(self, other):
if not isinstance(other, Playlist):
return NotImplemented
return Playlist(self._songs + other._songs)
What this tests: __len__, __getitem__ (with slices), __iter__, __contains__, __add__, copying a mutable argument, and delegating to an internal list.
Slices are objects: p[1:3] calls __getitem__(slice(1, 3)). Passing the key straight to the inner list handles ints, negatives and slices at once.
Copy mutable arguments: list(songs or []) makes a private copy. Without it, the caller could change the playlist by changing their list, and Playlist() with a mutable default would share one list between instances.
collections.abc.Sequence gives you __iter__, __contains__, index, count and __reversed__ for free once you provide __len__ and __getitem__. In real code that is the cleanest start.
What an interviewer might ask next: Add __eq__ so that two playlists with the same songs are equal, and __repr__. (And __hash__ only if the playlist cannot change.)
VISIBLE = 3
CASES = [
('p = Playlist(["a", "b", "c"])\nresult = (len(p), p[0], p[-1])', (3, 'a', 'c'), 'length and indexing'),
('p = Playlist(["a", "b", "c", "d"])\nresult = p[1:3]', ['b', 'c'], 'slicing gives a list'),
('p = Playlist()\np.add("x")\np.add("y")\nresult = list(p)', ['x', 'y'], 'add and loop'),
('p = Playlist(["a", "b"])\nresult = ("a" in p, "z" in p)', (True, False), 'membership'),
('r = Playlist(["a"]) + Playlist(["b", "c"])\nresult = (type(r).__name__, list(r))', ('Playlist', ['a', 'b', 'c']), 'addition gives a new playlist'),
('result = error_of(lambda: Playlist(["a"]) + ["b"])', 'TypeError', 'adding a list is an error'),
('songs = ["a"]\np = Playlist(songs)\nsongs.append("b")\nresult = len(p)', 1, 'the argument is copied'),
('a = Playlist()\nb = Playlist()\na.add("x")\nresult = len(b)', 0, 'playlists are independent'),
('p = Playlist(["a"])\nresult = error_of(lambda: p[5])', 'IndexError', 'a bad index'),
]