Summary: in this tutorial, you’ll learn about Python multiple inheritance and how method order resolution works in Python.
Introduction to the Python Multiple inheritance. #
When a class inherits from a single class, you have single inheritance. Python allows a class to inherit from multiple classes. If a class inherits from two or more classes, you’ll have multiple inheritance.
To extend multiple classes, you specify the parent classes inside the parentheses () after the class name of the child class like this:
class ChildClass(ParentClass1, ParentClass2, ParentClass3):
passCode language: Python (python)The syntax for multiple inheritance is similar to a parameter list in the class definition. Instead of including one parent class inside the parentheses, you include two or more classes, separated by a comma.
Let’s take an example to understand how multiple inheritance works:
First, define a class Car that has the go() method:
class Car:
def go(self):
print('Going')Code language: Python (python)Second, define a class Flyable that has the fly() method:
class Flyable:
def fly(self):
print('Flying')Code language: Python (python)Third, define the FlyingCar that inherits from both Car and Flyable classes:
class FlyingCar(Flyable, Car):
passCode language: Python (python)Since the FlyingCar inherits from Car and Flyable classes, it reuses the methods from those classes. It means you can call the go() and fly() methods on an instance of the FlyingCar class like this:
if __name__ == '__main__':
fc = FlyingCar()
fc.go()
fc.fly()Code language: Python (python)Output:
Going
FlyingCode language: Python (python)Here’s the complete program:
class Car:
def go(self):
print('Going')
class Flyable:
def fly(self):
print('Flying')
class FlyingCar(Flyable, Car):
pass
if __name__ == '__main__':
fc = FlyingCar()
fc.go()
fc.fly()Code language: Python (python)Output:
Going
FlyingCode language: Python (python)Method resolution order (MRO) #
When the parent classes have methods with the same name and the child class calls the method, Python uses the method resolution order (MRO) to search for the right method to call. Consider the following example: