Sitemap

Python: The Complete inheritance Tutorial

9 min readDec 28, 2018

--

Press enter or click to view image in full size

What to do when objects are Alike? We gonna discuss in detail about all required concepts and their implementation. I am assuming you have basic knowledge of python and OOP. Even if you haven’t ever heard of inheritance or you have worked with it this tutorial should be helpful to you.

Inheritance

Let’s say I am creating a Schooling system some of the classes will be:

Simple Classes example

Ok, so both Person and Employee class share a lot of similar code, whenever in programming you find yourself duplicating the code you are doing it wrong.

So when objects are very similar to each other to follow DRY(Do not Repeat Yourself) principle we use inheritance(but not always).

As the name suggests inheritance refers to inheriting a class(i.e. it’s attributes and methods) by other class. Just like you inherit hair colour or eyes from your parents.

The class whose properties is being inherited is called Parent Class(or superclass) whereas the one which inherits called child class.

We use inheritance when we have “is a” relationship between objects. Like, an employee is a Person, a car is a vehicle, a dog is an animal.

Using inheritance on our previous example we have:

Ok, so what we did?

  • To make Employee class child-class (or sub-class) of Person class we passed Person as a parameter to Employee. That’s how we inherit one class from other.
  • To access attributes and methods of parent class we use super() method.
  • We know both objects are similar but not same. That’s why we extended parent class __init__ methods in child class Employee to add employee_id.
  • Since we didn't need to change the name method we haven’t override or extended it. We can directly access name method from Employee object.

This is a basic example of Inheritance, no problem if you didn’t get everything as the tutorial progress you will.

Everything is inherited

Well you may know everything in python is an object. Also all classes by default is inherited from built-in Object class implicitly (you didn’t need to write it).

Overriding attributes and Methods

Well override.py says all.

Extending Methods

We have extended our __init__ method in the previous examples. Let’s learn more about it.

The output of the following code will be

bow bow
meow meow

This also goes with the real world, both cat and dog speak but differently.

This is a very simple example of method extending. The __init__ method is a common use case of the method extending. Unlike method overriding we can use both parent class logic/code and additional code required by child-class by extending method. Thanks to super().

Multiple Inheritance

A class may inherit properties from more than one class. You may have inherited your hairs from your Father and eyes from your Mother.

A simple example of Multiple Inheritance:

So, I don’t know why but we are creating a Robot which is similar to a Dog, that’s why we need to inherit it from both Robot and Dog class.

We have to use <class_name>.__init__ to initialize our RoboDog class with both parent classes (Robot and Dog) attributes and methods.

So we got a way to reference both parent class but what about methods. Since both Robot and Dog has a walk() method which one will be used?

When we search for an attribute in a class that is involved in python multiple inheritance, an order is followed. First, it is searched in the current class. If not found, the search moves to parent classes. It follows left to right order or depth-first. for ex. in RoboDog class Robot is passed first hence is more on the left side than Dog so it is ordered before Dog class.

This order is called Method Resolution Order (MRO). In our previous example order is:

  1. RoboDog
  2. Robot
  3. Dog
  4. Object (built-in python class, all classes inherited from)

i.e. Output of code is :

I am walking using my wheels

But what if for some crazy reason you want to use walk() method of Dog class on RoboDog object but you didn’t want to change the order of inheritance?

Just use this:

Dog.walk(Pika)

So, till now Multiple inheritance seems great but it’s considered as evil by many programmers. Java doesn’t even support multiple inheritance through classes. But there is another group of programmers which belief this widespread criticism of multiple inheritance is due to improperly implementation and usage of multiple inheritance. Python have really good approach towards multiple inheritance.

Now we gonna look at a common problem with multiple inheritance and how python solves it.

The Diamond Problem

Press enter or click to view image in full size
Diamond Inheritance problem | source: freecodecamp.org

This problem arises when a class is inherited from two base classes which themselves inherited from a class.

Following is a simple example of Diamond inheritance

Output:

I am class C

This looks good so far. But this has a problem.if we want to use methods of the parent class we got some problem. See

The output of the following code:

I am Superclass
I am ClassA
I am Superclass
I am ClassB
I am ClassC
2 1 1 1

So, you can see Superclass is called twice. The reason is pretty simple, Both ClassA and ClassB call Superclass respectively.

Well, this is just a dummy example but in real applications, when we have classes with large data and use, this redundant call is very harmful.

Now obviously there is a workaround. But in most of the Object-oriented language, we have to write sophisticated code. I will not go in detail about the workarounds because python has a pretty simple solution to this problem with its Super method. well, literally super() method.

I am Superclass
I am ClassB
I am ClassA
I am ClassC
1 1 1 1

So, a simple method solved the multiple inheritance problems. This shows how well-designed python is. But how? How python or super() method decides what to call and when to call. Remember MRO we talked about earlier? Yup, it helped us again. It is based on the “C3 superclass linearisation” algorithm. This is called a linearisation because the tree structure is broken down into a linear order.

Get Raj Dhakad’s stories in your inbox

Join Medium for free to get updates from this writer.

It converts the inheritance tree into a list. We will not get into the detail of this algorithm in this tutorial but you can see the list using:

print(ClassC.mro())

Output:

[<class '__main__.ClassC'>, 
<class '__main__.ClassA'>,
<class '__main__.ClassB'>,
<class '__main__.Superclass'>,
<class 'object'>]

So first ClassC calls ClassA, then ClassA (rather than Superclass) calls ClassB and then ClassB calls Superclass.

The algorithm uses the next method to call classes respectively. Also, ClassC calls ClassA first because ClassA is passed first to ClassC.

Multiple Inheritance Vs Composition

Even though it’s easy to use mulitiple inheritance in Python, still it’s a complex concept. Very Often handling it is tricky, you have to remember the whole inheritance tree or waste your time looking what comes from where?

There a few design alternatives to multiple inheritance among which most prefered is composition.

Still, this is very subjective and depends on the usage. Both inheritance and Composition our fundamentals to OOP.

Avoid multiple inheritance at all costs, as it’s too complex to be reliable. If you’re stuck with it,then be prepared to know the class hierarchy and spend time finding where everything is coming from.

Use inheritance only when there are clearly related reusable pieces of code that fit under a single common concept or if you have to because of something you’re using.

— Zed Shaw (Learning python the hard way)

The widespread prejudice that multiple inheritance is something “dangerous” or “bad” is mostly nourished by programming languages with poorly implemented multiple inheritance mechanisms and above all by improper usage of it.

— Bernd Klein (python-courses.eu)

As a rule of thumb, if you think you need multiple inheritance, you’re probably wrong, but if you know you need it, you’re probably right.

— Dusty Phillips (Python 3 Object-oriented Programming)

Composition

I know this tutorial is about inheritance, But we gonna discuss it’s the biggest rival composition because both patterns/concepts try to achieve the same.

Generally, we use Composition in a “has-a ” or “part-of” relationship. For eg. Book has a chapter, Car has a tank, the tyre is part of car

The idea behind Composition is fairly simple, Create an object of Class A inside Class B and use that object to access properties of class A inside Class B. Following example will make it more clear:

Output:

Chapter 1: Welcome is taken from Best Book by RD from RD-pubs
RD
Best Book by RD from RD-pubs

All we did is Created a Book object (book_obj) inside class Chapter. Then we can access attributes and methods of Book class using Chapter class Object (first_chap).

One thing to Note here is if we delete our chapter object, first_chap the book object will also be deleted. It’s justifiable in some cases but what if, you deleted first_chap from your Book Best Book to add another chapter say zero_chap. We have Aggregation to take care of it.

Aggregation

Aggregation is very similar to Composition, the difference is rather creating an object of Class A inside Class B, we first create an object of Class A separately and then pass it to Class B’s __init__ method. Like this:

Now even if we delete first_chap still we have our book_obj to add another Chapter object to it.

Using Composition instead of Multiple Inheritance

Well, till now we use Composition for a has-a relationship. Let’s use it as an alternative to multiple inheritance.

Going back to our RoboDog example Dog and Robot are the part of RoboDog’s characteristics or RoboDog has characteristics of Robot and Dog.

Output:

I am walking using my wheels
Bow Bow
Serve my Master

Composition decreases the complexity of the code and makes things easier to manage.

But, I will again say Composition vs Multiple-Inheritance is still subjective to your needs. Surely composition makes things easier but in some cases, you have to use Multiple-inheritance.

Abstract Base Classes

Abstract Base Class (or ABC because we like three-word acronym) is simply a class which just represent an abstract idea not it’s implementation. ABC class is like a template for other classes to use and follow. An instance/object of an ABC class can’t be created, nor it initializes also the sub-classes have to implement the methods of ABC class. Don’t worry the following example will make it clear.

Output:

25

Say we are creating a math-related software more specifically something which deals with shapes. We created a Shape class and defined some methods in it. Since different shapes have different properties we didn’t implement these methods rather just passed them for sub-classes like the Square.

The reason we do it is to make sure all instance(objects) of class Shape have area and perimeter methods. But this is not an abstract base class. Because we can create an object of Shape which nor makes sense nor goes with the definition of ABC classes. Also Square class didn’t have perimeter method still it works.

So how can we implement ABC class? well actually Python didn’t support Abstract class but, it has a module which does so. This module is called — for obvious reasons — abc.

How to make an ABC class?

We need to import ABC class and abstractmethod decorator from abc module, then inherit the required class from ABC class (Shape class in our example) and use abstractmethod decorator on methods you want sub-class to implement.

You need at least one abstractmethod in ABC class, not all methods need to be an abstractmethod. Use abstractmethod decorated only on methods that must be implemented by sub-classes(like the Square class in our example must have area and perimeter methods).

Now, let’s make Shape class an abstract base class.

Output

...
shape_obj = Shape()
TypeError: Can't instantiate abstract class Shape with abstract methods area, perimeter

See now, we got an error because we can’t create an object of ABC class. (shape_obj = shape() is invalid now).

Even if we remove shape_obj = shape() from shape_is_abc.py file, we will get this error

square_obj = Square(5)
TypeError: Can't instantiate abstract class Square with abstract methods perimeter

because we have two abstract methods area and perimeter but only one is implemented in the Square class.

The correct code will be:

Output:

25
20

Conclusion

We have talked about almost all major concepts related to inheritance. Thanks for reading the whole stuff. The objective of this tutorial is to explain concepts that’s why I used simple examples which may not resemble the real world programs. But this tutorial will definitely help you with inheritance, at least I hope so.

Sources:

Some of the sources I used as a reference and you can use to learn more about inheritance, OOP and python in general. :

Python-Courses.eu

Python 3 Object-oriented Programming by Dusty Phillips

ProgrammingKnowledge Youtube channel

StackOverflow

Programiz.com

Learning Python the Hard-way by Zed Shaw

You can follow me or talk to me at:

My twitter account (it’s very new)

My Github account

You can share your valuable feedbacks or queries in comments below and if you like to you can follow this Medium blog for more posts related to python, Django or may me programming in general.

Thank you!

--

--