Summary - Inheritance
- Python course
- Intermediate
- Lesson 12/116
- 5 min
Combine super and override to write a shape hierarchy.
Summary - Inheritance
In this group you learned inheritance, super(), overriding, multiple inheritance and isinstance/issubclass. A child class writes the parent in parentheses; super() calls parent methods.
With overriding the child redefines a parent method. Multiple inheritance uses comma-separated parents; MRO order decides. Now we will combine these pieces into one class.
Practice Combine the Dog class
Define the Animal class; add def __init__(self, species): with self.species = species in the body and def speak(self): with print("Sound"). Then define class Dog(Animal):; add def __init__(self, name): with super().__init__("dog") and self.name = name; add def speak(self): with print("Woof"). Then call d = Dog("Rex"), print(d.name) and d.speak().
Starter code
# Combine the Animal and Dog classesSample solution
# Combine the Animal and Dog classes
class Animal:
def __init__(self, species):
self.species = species
def speak(self):
print("Sound")
class Dog(Animal):
def __init__(self, name):
super().__init__("dog")
self.name = name
def speak(self):
print("Woof")
d = Dog("Rex")
print(d.name)
d.speak()Expected output
Rex Woof
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is done inside child __init__?
- Parent __init__ is ignored
- Class name is changed
- Parent class is deleted
- super().__init__(...) is called Correct answer
Explanation: Inside child __init__, super().__init__(...) is called explicitly.
2 Match the concepts
| Term | Meaning |
|---|---|
class Dog(Animal) |
Inheritance |
super() |
Parent call |
def speak(self) |
Override |
3 Complete the child class definition
class Dog(____):
pass
class Dog(Animal):
pass
Explanation: Dog inherits from Animal.