Exercises
Magic Methods
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Give Basket a length, so len() works and an empty basket is falsy.
Python
class Basket:
def __init__(self, items):
self.items = items
print(len(Basket(["a", "b"])))
print(bool(Basket([])))__len__ returns an int, and bool() falls back to it.
class Basket:
def __init__(self, items):
self.items = items
def __len__(self):
return len(self.items)
print(len(Basket(["a", "b"])))
print(bool(Basket([])))Exercise 2Passed
Two equal points collapse to one in a set. Make that work.
Python
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return (self.x, self.y) == (other.x, other.y)
print(len({Point(1, 2), Point(1, 2)}))Defining __eq__ removes the default hash. Add one that agrees with it.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return (self.x, self.y) == (other.x, other.y)
def __hash__(self):
return hash((self.x, self.y))
print(len({Point(1, 2), Point(1, 2)}))Exercise 3Passed
Make Playlist loopable and support 'in'.
Python
class Playlist:
def __init__(self, songs):
self.songs = songs
p = Playlist(["a", "b"])
print([s for s in p])
print("b" in p)__iter__ can hand back iter() of what it wraps.
class Playlist:
def __init__(self, songs):
self.songs = songs
def __iter__(self):
return iter(self.songs)
p = Playlist(["a", "b"])
print([s for s in p])
print("b" in p)