How to use Inheritance to express hierarchy in Python code

We often have an idea that we would like to turn into code. This becomes very easy to do when we know what inheritance is and how to implement it in Python. This is because in reality, there is hierarchy and this is why inheritance is needed.

Inheritance is a concept that finds application in code. It is when one piece of code inherits some properties from another piece of code. This helps create hierarchical relations.

Let’s assume that we have the idea that all living organisms have 3 attributes: age, weight and height. When we say ‘all organisms’ this, in Python, means that we create a class. Below, we create a class, which essentially describes the attributes of all living organisms. Each living organism is represented by this ‘self’.

Now, let’s say that we want to express the idea that all animals are living organisms. And that animals also have the property ‘legs’, which indicates how many legs they have, and most of them have 4 legs. Again, in this case we say ‘every animal’, meaning that we need to create a class.

In addition, we want to express the idea that every turtle is an animal, and in addition, it has the attribute that it has 2 eyes. In other words, every turtle has 2 eyes. There are no turtles with a different number of eyes.

Below you can find the code that implements these ideas. You can also download this code so you can run it on your own. You can also read some additional analysis below.

Subscribe to The Algorithmic Economist to read the rest.

Become a paying subscriber of The Algorithmic Economist to get access to this post and other subscriber-only content.

Already a paying subscriber? Sign In

A subscription gets you:
4 articles per month on real-world case studies (insights, code)
4 articles per month on research (academia, industry), explained in simple language