Chapters
Python114 chapters

Exercises

Inheritance

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

Exercise 1

Make Dog inherit from Animal and override speak to return woof.

Python
class Animal:
    def speak(self):
        return "some sound"

# define Dog
print(Animal().speak())
print(Dog().speak())
Exercise 2

Dog forgets to run the parent's setup, so name is missing. Fix it.

Python
class Animal:
    def __init__(self, name):
        self.name = name

class Dog(Animal):
    def __init__(self, name, breed):
        self.breed = breed

rex = Dog("Rex", "collie")
print(rex.name, rex.breed)
Exercise 3

A car is not an engine. Rewrite this to hold an Engine rather than inherit from it.

Python
class Engine:
    def start(self):
        return "engine running"

class Car(Engine):
    pass

print(Car().start())