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.
Figure 32.1: The 5 types of inheritance supported in Python: Single, Multiple, Multilevel, Hierarchical, and Hybrid.
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()
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?
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!
object base class. If a class definition specifies no parent (e.g. class Car:), it automatically inherits from object.