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 Bootcamp: Go from zero to hero in Python
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:
class Subclass(SuperClass1, SuperClass2, SuperClass3, ..):
You can visually see that as:
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:
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.
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.
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.