A class can inherit from multiple super classes. Multiple inheritance is an extension of standard or single inheritance. The principle remains the same: a class inherits from another class.

Multiple inheritance is the idea of inheriting from more parent classes. A class can inherit from 2,3 or a multiple of classes.

Related course: Complete Python Programming Course & Exercises

Example

Introduction

A class can inherit from a multiple of classes in Python (this isn’t always the case for other programming languages).
If you create a class, you can let it inherit from parent classes (sometimes called super classes).

The class itself can be named subclass, because it has several parents.

If a class inherits from super classes, it will get all their attributes and methods. If you have 4 super classes, it will simply inherit all of them.

The general format is:

1
class Subclass(SuperClass1, SuperClass2, SuperClass3, ..):

You can visually see that as:

multiple inheritance

Multiple inheritance

In the program below are defined two super classes: Human and Coder. The class Pythonista inherits from both classes by iusing this line of code:

1
class Pythonista(Human, Coder):

The program goes on by creating an object. The object has attributes from all 3 classes: the super classes and itself. If you define methods in super classes or the class, the object will have all methods.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Human:
name = ""

class Coder:
skills = 3

class Pythonista(Human, Coder):
version = 3

obj = Pythonista()
obj.name = "Alice"

print(obj.name)
print(obj.version)
print(obj.skills)

Criticism

Critics of multiple inheritance point out that it increases complexity and makes it harder for code to be reusable. In that point that, if you were to copy a class to a new program, you’d have to copy all the super classes too.

That may be fine for one class, but if your code has multiple inheritance everywhere, it will be hard to use parts as reusable components for other programs.

Indeed, adding multiple inheritance to a program creates strong cohesion between the classes. But that doesn’t mean it’s not a useful tool.

If you are a beginner, then I highly recommend this book.

Exercises

Try these exercises:

  • Do all programming languages support multiple inheritance?
  • Why would you not use multiple inheritance?
  • Is there a limit to the number of classes you can inherit from?

Download answers in exercise section above.

Download examples