Inheritance in Python
Posted on Fri 13 September 2019 in Python • 2 min read
As Python is a high level, general purpose programming language, which supports users to define their own types using classes, which are most often following the concept of object-oriented programming. Object-oriented programming is a type of software design in which users not only define the data type (eg, int) of a data structure, but also the types of functions that can be applied.
Object-oriented programming is built up of a lot of concepts, to name a few:
- Inheritance
- Abstraction
- Class
- Encapsulation
- so on
This post will cover an introduction to the concept of inheritance using Python and the animal kingdom.
First off, we are going to start by defining our 'base' class (also known as abstract class) of our Animal with common properties:
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Now that we have our base class, we can define a subclass 'Dog' that will be able to speak if we define the function inside, but we can also see that it derives from it's parent class 'Animal' by printing out it's family.
1 2 3 4 5 6 7 8 9 10 11 |
|
Which will print out:
1 2 |
|
See my post on dunders (double underscores) to get a better understanding of how the __init__ function is working: https://jackmckew.dev/dunders-in-python.html
Now we can define any subclass which can derive from our parent class 'Animal', or even more we can derive a class from 'Dog' and it will have all it's properties:
1 2 3 4 5 6 7 |
|
Which will also print:
1 2 |
|
Now what if we wanted to specify the family that all of our dog classes are, we can do this by overriding their parent class (similar to how we are overriding the speak function):
1 2 3 4 5 6 7 8 9 |
|
Which then when we run both the below code:
1 2 3 4 5 6 7 8 9 10 11 |
|
We will now get:
1 2 3 4 |
|
You should now be comfortable in understanding how inheritance works. Normally, it's best practice to inherit only from a single parent class when creating subclasses. As multiple inheritance makes your programs less complicated and easier to manage. However, for large programs, it is very difficult to avoid multiple inheritance.