Multiple level Inheritance

Multiple level Inheritance

In Python, there are several types of inheritance:

  1. Single Inheritance
  2. Multiple Inheritance
  3. Multi-Level Inheritance
  4. Hierarchical Inheritance
  5. Hybrid Inheritance

In this article we will be discussing about Multiple level Inheritance. Multiple inheritance is a feature of object-oriented programming languages, including Python, where a class can inherit attributes and methods from more than one base class. This allows for greater flexibility and the combination of behaviors and characteristics from different classes. Below is the sample code:


class Animal:
    def speak(self):
        print("Animal makes a sound")

class Walker:
    def walk(self):
        print("Walker is walking")

class Dog(Animal, Walker):
    def bark(self):
        print("Dog barks")

# Creating an instance of Dog
dog = Dog()
dog.speak()  # Inherited from Animal
dog.walk()   # Inherited from Walker
dog.bark()   # Defined in Dog
        

But in scenarios Multiple level Inheritance raises "Diamond Problem". The diamond problem is when two classes inherit from a single base class, and another class inherits from both of these classes. This creates an ambiguity because it's not clear which path to take to inherit from the topmost class.


When a method is called on an instance, Python needs to know which method to execute if the method is defined in multiple base classes. Python uses the C3 linearization algorithm (also known as the C3 superclass linearization) to determine the MRO.

You can view the MRO of a class using the __mro__ attribute or the mro() method.

Lets see this with sample example

class A:
    def show(self):
        print("Show from A")

class B(A):
    def show(self):
        print("Show from B")

class C(A):
    def show(self):
        print("Show from C")

class D(B, C):
    pass

d = D()
d.show()
print(D.__mro__)
        

In this case, D inherits from both B and C, which in turn inherit from A. Python's MRO resolves the ambiguity.

# Output
Show from B
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)        


要查看或添加评论,请登录

社区洞察

其他会员也浏览了