Multiple inheritance is a feature in object-oriented programming where a class can inherit attributes and methods from more than one parent class. This can lead to more complex and flexible class designs, but it also introduces additional complexity and potential issues, such as the Diamond Problem.
Multiple inheritance allows for:
Let’s look at a practical example to understand multiple inheritance better.
class Animal:
def __init__(self, name):
self.name = name
def move(self):
print(f"{self.name} is moving")
class Swimmer:
def swim(self):
print(f"{self.name} is swimming")
class Duck(Animal, Swimmer):
def quack(self):
print(f"{self.name} says Quack!")
if __name__ == "__main__":
daffy = Duck("Daffy")
daffy.move() # Output: Daffy is moving
daffy.swim() # Output: Daffy is swimming
daffy.quack() # Output: Daffy says Quack!
Animal:
__init__ method initializes the name attribute.Swimmer:
Duck:
name attribute and move method from the Animal class.swim method from the Swimmer class.quack method specific to Duck.class A:
def hello(self):
print("Hello from A")
class B(A):
def hello(self):
print("Hello from B")
class C(A):
def hello(self):
print("Hello from C")
class D(B, C):
pass
if __name__ == "__main__":
d = D()
d.hello() # Output: Hello from B (Method Resolution Order)
In this example, D inherits from both B and C, which both inherit from A. When calling hello on an instance of D, Python uses the Method Resolution Order (MRO) to determine which method to call.
Python uses the C3 linearization algorithm to determine the MRO, which ensures a consistent order for method resolution.
print(D.mro())
# Output: [<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]