class Ambulance(Vehicle):
def __init__(self, reg_number):
# This calls the constructor of the parent (super), and passes the reg
# number across to it
super().__init__(reg_number)
49 Inheritance
In Object Oriented Programming, we can also have classes that are based on other classes. This is known as inheritance.
In our example, we could create a Vehicle class that has attributes and methods applicable to all vehicles, and then create an Ambulance class which inherits this stuff but adds its own ambulance-specific things too.
This improves efficiency if we need to write multiple classes that are similar.
In this example, the Vehicle class would be known as the parent and the Ambulance class as the child.
You can see how powerful this may be if we have lots of different child classes.
49.1 Inheritance in Python
Inheritance is really easy to do in Python.
We’ll start by creating our parent class.
Note we don’t have to do anything special here - we just define our class as normal, but only containing the things we want to be common to all child classes.
Let’s create our first child class.
The key bits here are as follows:
Notice when we create the Ambulance
class, we put the Vehicle
class inside the brackets at the beginning.
This tells the class to use the Vehicle
class as the parent class.
We then need to run the line
super().__init__()
to call the constructor of the parent class.
In our case, we also want to pass the reg_number
to the parent class, so our line looks like this.
super().__init__(reg_number)
The full class looks like this:
You can see that other than the __init__
method, the rest of the code (i.e. each method) is actually the same as our earlier ambulance code.
Let’s create two more child classes: bus
and car
.
When we want to instantiate an ambulance, we do it exactly the same as before.
It’s just we’ve saved ourselves having to rewrite some of the definitions that are common to vehicles.
If the child class contains no differences in its constructor from the parent class, then you don’t need to define the constructor at all in the child class.
It will automatically use the parent class constructor on instantiation.