top of page
Search
Writer's pictureMaia

Python Tips Series: Multiple Inheritance



In the previous post, we looked at the fundamentals of Python Inheritance and only focused on single inheritance. In this continued article, we will look at Multiple Inheritance where one class can inherit from more than one class.

In Python, a class can be derived from one or more base classes. This is called multiple inheritance. This type of inheritance allows the features of all the base classes are inherited into the child class. The syntax for multiple inheritance is very similar to single inheritance.

Let's define a class that inherits from two other classed.

We can check if Child class is a subclass of both Base1 and Base2. As we can see below it is a subclass of both.

Let's define some more meaningful classes with real behaviors that show multiple inheritance.

In the example above, we see that the Fish class inherits only from single class. Dog class inherits from three other classes. And, Programmer class inherits from four other classes. We know that or at least we want to model that a Fish can swim, but can't run; a Dog can swim and run. But both Fish can Dog can't program in Python! Only a Programmer can code Python.

We see that Fish, Dog and Programmer by themself they didn't define any of these methods, but they can use it because they inherit them from multiple base classes.

If we try to use a method that is not from any of classes that a class is derived from, it will cause errors.

There is another type of inheritance where a class inherits from multiple classes called Multilevel Inheritance. Which is basically similar to Single Inheritance where a class inherit from another class and this base class is inherited from another class.

We see that Programmer inherit from both Animal and Animal in turn inherit from Runable, so a Programmer can use run() method, even though this method is not defined either in Animal nor Pythonable directly.

That's the fundamentals of multiple inheritance.


Happy Inheriting!



Recent Posts

See All

Comments


Post: Blog2_Post
bottom of page