Chapters
Python114 chapters

Exercises

Polymorphism

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

Exercise 1

Three unrelated classes, each with speak. Loop over one of each and print what they say.

Python
class Dog:
    def speak(self):
        return "woof"

class Cat:
    def speak(self):
        return "meow"

class Robot:
    def speak(self):
        return "beep"

# loop over one of each
Exercise 2

Make Playlist loopable and countable by adding two dunder methods.

Python
class Playlist:
    def __init__(self, songs):
        self.songs = songs

p = Playlist(["a", "b", "c"])
print(len(p))
print([song for song in p])
Exercise 3

Make Shape abstract so a subclass without area cannot be built.

Python
class Shape:
    def area(self):
        pass

class Blob(Shape):
    pass

try:
    Blob()
    print("built one, which it should not have")
except TypeError:
    print("refused, as it should be")