Python – Multiple Class Inheritance
Python supports the idea of multiple class inheritance; that is a class can inherit from one or more other classes (many object-oriented languages limit inheritance to a single class such as Java and C#).
The syntax for defining multiple inheritance in Python allows multiple superclasses to be listed in the parent class list (defined by the brackets following the class name). Each parent class is separated by a comma. The syntax is thus:
class SubClassName(BaseClassName1, BaseClassName2, … BaseClassNameN): class-body
class Car: """ Car class""" class SportzCar: """ Sportz Car""" class MyCar(Car, SportzCar): """ My Car is Sports Car"""
In above example, we can say that the class MyCar inherits all the attributes (data) and methods (behaviour) defined in classes Car , SportsCar .
Challenge Faced in Multiple Inheritance
One of the fundamental questions that this raises is, how inheritance of behavior managed within a multiple inheritance hierarchy. The challenge that multiple inheritance possesses is illustrated by adding a couple of methods to the class hierarchy we are looking at.
In this method, we have added the method move() to both the classes Car and SportsCar .
As “diamond inheritance problem“, Which version of the method move() will be run when an instance of the MyCar class is instantiated and we call my_car.move() ?
In Python 3, a breadth first search is used to find methods defined in parent classes; this means that when the method move() is called on
MyCar, it would first look in Car ; it would then only look in SportsCar if it could not find a method move() in Car.
As a result, it will find the version in Car first and use that version. Hence, when we execute below code,
class Car: """ Car class""" def move(self): print("In Car class - move method") class SportzCar: """ Sportz Car""" def move(self): print("In SportsCar class - move method") class MyCar(Car, SportzCar): """ My Car is Sports Car""" my_car = MyCar() my_car.move()
The output will be as below,
In Car class - move method
This shows that the order in which a class inherits from multiple classes is significant In Python.
In this article, we saw about syntax, example of multiple inheritance in python. And then how the diamond inheritance problem is handled in Python for same method name.
Check out other post related to Python