Inheritance and super()
Build new classes on top of existing ones instead of starting from scratch
super() is how the child cooperates with the parent instead of quietly replacing it.
- define a derived class with
class Child(Parent):and explain the is-a relationship, - call the parent's
__init__(and other methods) withsuper(), - override a method and know when to extend it versus replace it,
- decide between inheritance and composition using is-a versus has-a,
- read a small class hierarchy and predict which method runs.
1. Base classes and derived classes
You already know how to write a single class with __init__ and methods. Inheritance is what happens when two classes share a lot of behaviour and you do not want to copy it twice. Suppose you are modelling animals. Every animal has a name and can eat; only some can bark. Rather than repeat the name/eat code in Dog, Cat and Bird, you put the shared parts in one base class and let each specific animal derive from it.
The test for inheritance is the is-a relationship: a Dog is an Animal, a SavingsAccount is a BankAccount. If that sentence sounds true, inheritance is a candidate. If instead you would say has-a (a Car has an Engine), that is composition, which we cover in section 6.
class Animal: # base / parent class
def __init__(self, name):
self.name = name
def eat(self):
return self.name + " is eating"
class Dog(Animal): # derived / child class -- Dog IS-A Animal
def bark(self):
return "Woof!"
d = Dog("Rex")
print(d.eat()) # inherited from Animal
print(d.bark()) # defined on Dog
Output:
Rex is eating
Woof!
Notice that Dog never defines __init__ or eat, yet d.eat() works. Python did not find eat on Dog, so it looked at the parent Animal and used that. That upward search is the heart of inheritance.