Implementing Multiple Inheritance in Python
Syntax for Multiple Inheritance
In Python, you can implement multiple inheritance by simply listing all the parent classes when defining a new class. The syntax looks like this:
class ChildClass(ParentClass1, ParentClass2, ParentClass3):
## class definition
pass
Here, ChildClass
inherits from ParentClass1
, ParentClass2
, and ParentClass3
.
Accessing Attributes and Methods
When you have multiple parent classes, you can access their attributes and methods using the same syntax as single inheritance:
obj = ChildClass()
obj.parent1_method() ## Calls a method from ParentClass1
obj.parent2_attribute ## Accesses an attribute from ParentClass2
Resolving Method Conflicts
If the parent classes have methods with the same name, Python uses the Method Resolution Order (MRO) to determine which method to call. You can inspect the MRO of a class using the __mro__
attribute or the mro()
function:
print(ChildClass.__mro__)
## (<class 'ChildClass'>, <class 'ParentClass1'>, <class 'ParentClass2'>, <class 'ParentClass3'>, <class 'object'>)
To explicitly call a method from a specific parent class, you can use the class name as a prefix:
obj = ChildClass()
obj.ParentClass1.parent1_method(obj)
Alternatively, you can use the super()
function to call a method in the next class in the MRO:
class ChildClass(ParentClass1, ParentClass2):
def my_method(self):
super().my_method() ## Calls the next method in the MRO
Real-world Example
Let's consider a real-world example of using multiple inheritance in Python. Imagine you have a Vehicle
class, a Flyable
class, and a Drivable
class. You can create a FlyingCar
class that inherits from all three:
class Vehicle:
def __init__(self, make, model):
self.make = make
self.model = model
def start(self):
print("Starting the vehicle.")
class Flyable:
def fly(self):
print("Flying the vehicle.")
class Drivable:
def drive(self):
print("Driving the vehicle.")
class FlyingCar(Vehicle, Flyable, Drivable):
def __init__(self, make, model):
Vehicle.__init__(self, make, model)
def takeoff(self):
self.fly()
self.drive()
flying_car = FlyingCar("LabEx", "FlyingCar 2000")
flying_car.start()
flying_car.takeoff()
In this example, the FlyingCar
class inherits from Vehicle
, Flyable
, and Drivable
, allowing it to have the functionality of all three parent classes.
By understanding the syntax, method resolution order, and conflict resolution techniques, you can effectively implement multiple inheritance in your Python projects.