Inheritance and Polymorphism in Python with examples

In this post, you can learn about inheritance and polymorphism in Python with examples. These two concepts are a cornerstone in programming. It doesn’t matter what programming language you are learning; you need to know these two topics.

If you are reading this post, I assume you already know what a class in programming is. If you are still not sure, you learn it in this post.

Inheritance and polymorphism example in python with examples

Inheritance in Python

Let’s see a definition of a python class that represents a person.

class Person:
    def __init__(self, name, surname, idNumber):
        self.name = name
        self.surname = surname
        self.idNumber = idNumber

In general, a person has a name, surname and id number. Those are the most common attributes in a person, and we are going to use them just as an example.

Let’s say now that we have to define a python class to represent students. The students will have name, surname, id and what degree they are enrolled. The class will be defined as follows:

class Student:
    def __init__(self, name, surname, idNumber, degreeEnrolled):
        self.name = name
        self.surname = surname
        self.idNumber = idNumber
        self.degreeEnrolled = degreeEnrolled

That’s great! We have our two classes defined and implemented.

But hold on, there are three lines of code that are just the same in the two classes.

One of the main principles of object-oriented programming is code-reuse. So anytime you see repeated code in your program, something must be wrong.

So, in this case, how can we fix this problem?

I guess you already know the answer: Inheritance.

Check the code below.

class Student (Person):
    def __init__(self, name, surname, idNumber, degreeEnrolled):
        super().__init__(name, surname, idNumber)
        self.degreeEnrolled = degreeEnrolled

There are two new things in the code above.

First, after the class name, you can see (Person). That means the class Student inherits from the class Person. The class student is the child (or derived) class, and the class Person is the parent (or base) class.

In this scenario, inherits means the class student now has all the attributes and methods defined for the class Person. So, you don’t need to write the same code again.

The second one is the first line in the constructor. This line of code calls the constructor of the parent class (Person) with the parameters name, surname and id. In other words, the line executes the constructor of the parent class.

You can see this in the following way, if you have a repeated code, you can embed that code in place, and anytime you need the code you execute it from that place.

In the example above the code, repetition is avoided by using inheritance. But in many other cases is avoided by using helper functions or classes. These functions and classes are a kind of containers for code that you can use in several places. That is another way to avoid code repetition.

As a final remark of this section, you can have a class hierarchy of any number of classes. For instance, class A inherits from class B, class B inherits from class C, class D inherits from class A, and so on. That is the basics of inheritance in python.

Polymorphism in Python

In python, it doesn’t make too much sense to talk about polymorphism.

Polymorphism happens when the static type is different than the dynamic type, among other conditions.

Python is not a strongly typed language, like Java for instance. What this means is that in python you don’t have to define the type of the variable.

The type is inferred from the value the variable is holding.

Let’s check the following examples in Python.

name = "John"

age = 30

The type of the variable name is string, and for the variable age, the type is integer.

Now let’s see the same example in Java.

String name = "John";
int age = 30;

In this case, you have to specify the type, before you assign a value to the variable. So, in Java, there are other things that we have to consider to have polymorphism. The same way, in another language, like C++, you have to consider more things than in Java.

You can read a full explanation here with examples in Java and C++.

In Python, because variables behave according to the value that is stored, we can say that polymorphism is native, and we don’t have to worry about it.

Let’s see the example below.

name = "John"
print (type(name))
name = 15
print(type(name))

The function type in python, receives a variable as a parameter and returns the type of that variable.

If you execute the code above, you will get the following result

<class 'str'>
<class 'int'>

This means that the type of the variable changes according to the value you assign to it. Which is the meaning of polymorphism. A variable that behaves differently according to its value.

What now?

Now you now Inheritance and Polymorphism in Python, you saw a couple of examples. What’s next?

As you can see, the topic is very easy to explain and understand. There are many videos about it showing many examples in just a few minutes.

But what will do you do with that knowledge now? How will you use it?

I wrote these questions for you because I want to think about the big picture here.

You are learning Python because you want to learn programming. You want to be able to do something with that knowledge.

Spoiler alert: What we do with programming is to solve problems. We model situations from the real-world and we implement the model using a specific programming language. We design an algorithm and then we implement it in a programming language.

What does it mean?

It means, a programming language (like Python), is a mean to an end, not the end itself. We use a programming language as a tool to solve problems, as a way to tell the computer what to do.

Before you can use a programming language to solve a problem, you need to know how to solve the problem. You have to model the solution first, and then you implement the model in your favourite programming language (or in the language the client asks you to use).

Just think about it for a moment. You meet someone that wants you to create a software for them.

The usual process is the person will describe a problem to you: i.e. I need a software to do my bookkeeping tasks. The ones in the market are too expensive and I want one with specific things I cannot find in the solutions that are out there.

The first thing you have to do is to learn how to do the bookkeeping yourself, manually. Then you start the design of your system. You first design the architecture, then the database, UML class diagrams that help you understand what you have to implement, etc.

So, the client does not tell you to use inheritance and polymorphism in Python. They will ask you to solve a problem. Also, only after you create your whole model or design, is that you will write your first line of code towards the solution of the problem.

That is why I always emphasised in the paradigm, the models, the design, the thinking and not in the specific programming language.

But we still have to learn the specific programming language. That is one of the reasons why I’m writing this post.

If you want to be good at programming, you have to focus on the fundamentals, on algorithms, on the paradigm. Don’t spend too much time on one programming language. It is better to learn the fundamentals, that is what will empower you. It is what will allow solving problems by using programming, which I know might be your ultimate goal.

You can read further about the fundamentals in these posts: Road map to learn programming: don’t learn a language, how to learn algorithms in programming and OOP paradigm principles.

Summary

Inheritance and polymorphism are two of the main important concepts to master in programming.

They are implemented in different ways depending on the programming language you want to use. But the basics are the same. What happens is that some programming languages have explicitly implemented some of the requirements for polymorphism and others don’t.

It is important to learn programming problem-solving skills. This one must be your ultimate goal. If you cannot solve a problem with programming, there is no point in learning a programming language.

Potential clients or employers don’t know anything about programming. They will give you a problem to solve and you have to make many decisions before you can start typing your first line of code. The quality of your product (the software that you are going to create) depends mostly on those first decisions and less in the code you write in your favourite programming language.

If you don’t want to miss the next posts in the topic (OOP in Python), subscribe to the newsletter.

H@ppy coding.