Python Single, Multiple, and Multi-Level Inheritance Types

  • Read
  • Discuss

Single Inheritance in Python:

In single inheritance, a class is derived from a single base class. For example:

class Parent:
    def __init__(self):
        self.value = "Parent"

class Child(Parent):
    def __init__(self):
        super().__init__()
        self.value = "Child"

In the above example, the Child class inherits the properties and methods of the Parent class. The super() function is used to call the init method of the Parent class in the Child class.

Multiple Inheritance in Python:

In multiple inheritance, a class can inherit properties and methods from multiple base classes. For example:

class Parent1:
    def __init__(self):
        self.value = "Parent1"

class Parent2:
    def __init__(self):
        self.value = "Parent2"

class Child(Parent1, Parent2):
    def __init__(self):
        super().__init__()

In the above example, the Child class inherits properties and methods from both Parent1 and Parent2 classes. The super() function is used to call the init method of the parent class in the Child class.

Multi-level Inheritance in Python:

In multi-level inheritance, a class can inherit properties and methods from a class that inherits from another class. For example:

class GrandParent:
    def __init__(self):
        self.value = "GrandParent"

class Parent(GrandParent):
    def __init__(self):
        super().__init__()
        self.value = "Parent"

class Child(Parent):
    def __init__(self):
        super().__init__()
        self.value = "Child"

In the above example, the Child class inherits properties and methods from the Parent class, which in turn inherits properties and methods from the GrandParent class. The super() function is used to call the init method of the parent class in the Child class.

Method Resolution Order

It’s worth noting that when using multiple or multilevel inheritance, Python follows a specific resolution order, called the Method Resolution Order(MRO) to determine the order in which it will look for methods on the base class. 

Leave a Reply

Leave a Reply

Scroll to Top