Python Inheritance & Polymorphism: Types, super() & Method Resolution Order

Inheritance is a cornerstone of Object-Oriented Programming that establishes an "is-a" relationship between classes. A Derived (Child) Class inherits attributes and methods from a Base (Parent) Class, enabling code reusability, modular hierarchy, and polymorphism.

Five Types of Python Inheritance Diagram

Figure 32.1: The 5 types of inheritance supported in Python: Single, Multiple, Multilevel, Hierarchical, and Hybrid.


1. Single Inheritance & Method Overriding with super()

In single inheritance, a derived class inherits from exactly one parent class:

class Person:
    def __init__(self, name: str, age: int):
        self.name = name
        self.age = age

    def introduce(self):
        print(f"Hi, I am {self.name}, age {self.age}.")

# Derived Class inheriting from Person:
class Student(Person):
    def __init__(self, name: str, age: int, roll_no: int, major: str):
        # Call parent constructor using super():
        super().__init__(name, age)
        self.roll_no = roll_no
        self.major = major

    # Method Overriding:
    def introduce(self):
        super().introduce()  # Call parent method
        print(f"I am a {self.major} student (Roll: {self.roll_no}).")

# Usage:
s = Student("Rohan", 21, 109, "BCA")
s.introduce()

2. Multiple Inheritance & The Diamond Problem

Python allows a child class to inherit from multiple parents simultaneously:

class Flyable:
    def move(self):
        print("I am flying through the air!")

class Swimmable:
    def move(self):
        print("I am swimming across the river!")

# Inherits from both parents:
class Duck(Flyable, Swimmable):
    pass

d = Duck()
d.move()  # Which move() is called? Flying or Swimming?

3. Method Resolution Order (MRO) & C3 Linearization

To resolve the order in which inherited methods are searched, Python uses the C3 Linearization Algorithm. You can inspect the MRO of any class using Class.mro() or Class.__mro__:

print("Duck MRO:", Duck.mro())
# Output: [Duck, Flyable, Swimmable, object]
# Because Flyable appears first in Duck(Flyable, Swimmable), its move() is executed!

Frequently Asked Questions (FAQ)

What is the ultimate root class of all objects in Python?

In Python 3, every class implicitly inherits from the built-in object base class. If a class definition specifies no parent (e.g. class Car:), it automatically inherits from object.
Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!