Exercises
Polymorphism
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
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
No inheritance needed; having the method is enough.
class Dog:
def speak(self):
return "woof"
class Cat:
def speak(self):
return "meow"
class Robot:
def speak(self):
return "beep"
for thing in [Dog(), Cat(), Robot()]:
print(thing.speak())Exercise 2Passed
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])__len__ and __getitem__ are enough for both.
class Playlist:
def __init__(self, songs):
self.songs = songs
def __len__(self):
return len(self.songs)
def __getitem__(self, index):
return self.songs[index]
p = Playlist(["a", "b", "c"])
print(len(p))
print([song for song in p])Exercise 3Passed
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")abc gives you ABC and abstractmethod.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
...
class Blob(Shape):
pass
try:
Blob()
print("built one, which it should not have")
except TypeError:
print("refused, as it should be")