Chapters
Python114 chapters

Exercises

Magic Methods

3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.

Exercise 1

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([])))
Exercise 2

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)}))
Exercise 3

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)