CS Pathfinder Logo CS Pathfinder

Unit 5 · Advanced Topics

Inheritance

Inheritance is a fundamental pillar of Object-Oriented Programming that allows a class to acquire the properties and behaviors of another class, enabling code reuse, hierarchical relationships, and logical modeling of real-world entities.

Table of Contents

University Definition

Inheritance is a mechanism in Object-Oriented Programming where a new class (called child class or derived class) inherits attributes and methods from an existing class (called parent class or base class). It promotes code reuse and establishes an "is-a" relationship between classes.

In Python, every class implicitly inherits from the built-in object class. When you create a class without specifying a parent, it inherits from object by default. The child class can use all public attributes and methods of the parent, add new ones, or override existing ones.

The general syntax for creating a child class is:

class ChildClass(ParentClass):
    pass

1. Single Inheritance

A child class inherits from exactly one parent class. This is the simplest and most common form of inheritance.

# Parent class
class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return f"{self.name} makes a sound"

# Child class
class Dog(Animal):
    def fetch(self):
        return f"{self.name} fetches the ball"

dog = Dog("Buddy")
print(dog.speak())    # Buddy makes a sound
print(dog.fetch())    # Buddy fetches the ball

University Exam Tip

In exam answers, always draw the inheritance diagram (Parent → Child arrow) alongside your code. Mention the "is-a" relationship: "Dog is an Animal". Universities often award extra marks for diagrams.

2. Multiple Inheritance

A child class inherits from two or more parent classes simultaneously. Python supports multiple inheritance directly.

class Mother:
    def eyes_color(self):
        return "Brown"

class Father:
    def height(self):
        return "5'10\""

class Child(Mother, Father):
    def name(self):
        return "Rahul"

c = Child()
print(c.eyes_color())  # Brown
print(c.height())      # 5'10"
print(c.name())         # Rahul

3. Multilevel Inheritance

A class inherits from a child class, forming a chain: Grandparent → Parent → Child.

class Animal:
    def eat(self):
        return "Eating..."

class Dog(Animal):
    def bark(self):
        return "Barking..."

class  Puppy(Dog):
    def wee(self):
        return "Wee wee..."

p = Puppy()
print(p.eat())   # Eating...
print(p.bark())  # Barking...
print(p.wee())   # Wee wee...

4. Hierarchical Inheritance

Multiple child classes inherit from a single parent class.

class Vehicle:
    def __init__(self, brand):
        self.brand = brand

    def info(self):
        return f"Brand: {self.brand}"

class Car(Vehicle):
    def drive(self):
        return "Car is driving"

class Truck(Vehicle):
    def load(self):
        return "Truck is loading"

car = Car("Toyota")
truck = Truck("Tata")
print(car.info())    # Brand: Toyota
print(car.drive())   # Car is driving
print(truck.info())  # Brand: Tata
print(truck.load())  # Truck is loading

super() Method

University Definition

The super() function returns a temporary proxy object that delegates method calls to a parent class. It is commonly used in the child class to call the parent class's __init__ method or overridden methods without explicitly naming the parent.

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

    def display(self):
        return f"Name: {self.name}, Age: {self.age}"

class Student(Person):
    def __init__(self, name, age, roll_no):
        super().__init__(name, age)  # Call parent constructor
        self.roll_no = roll_no

    def display(self):
        return f"{super().display()}, Roll No: {self.roll_no}"

s = Student("Priya", 20, "A001")
print(s.display())
# Output: Name: Priya, Age: 20, Roll No: A001

Method Overriding

University Definition

Method Overriding occurs when a child class provides a specific implementation of a method that is already defined in its parent class. The method in the child must have the same name and parameters as the parent method.

class Shape:
    def area(self):
        return 0

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14 * self.radius ** 2

class Rectangle(Shape):
    def __init__(self, length, width):
        self.length = length
        self.width = width

    def area(self):
        return self.length * self.width

shapes = [Circle(5), Rectangle(4, 6)]
for s in shapes:
    print(s.area())  # 78.5 then 24

Method Resolution Order (MRO)

When you call a method on an object of a class with multiple inheritance, Python follows the MRO (Method Resolution Order) to decide which parent class method to invoke. Python uses the C3 Linearization algorithm.

class A:
    def show(self):
        print("Class A")

class B(A):
    def show(self):
        print("Class B")

class C(A):
    def show(self):
        print("Class C")

class D(B, C):
    pass

d = D()
d.show()  # Class B (follows MRO: D → B → C → A)
print(D.__mro__)
# (<class 'D'>, <class 'B'>, <class 'C'>, <class 'A'>, <class 'object'>)

isinstance() Function

The isinstance() function checks if an object is an instance of a specified class or its subclasses.

d = Dog("Buddy")
print(isinstance(d, Dog))       # True
print(isinstance(d, Animal))    # True (parent class)
print(isinstance(d, object))    # True (base class)
print(isinstance(d, Puppy))     # False

Practical Example: University Exam Program

Problem: Create a class Employee with name and salary. Create a child class Manager that adds a department field. Print all details using super().

class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def display(self):
        return f"Name: {self.name}, Salary: {self.salary}"

class Manager(Employee):
    def __init__(self, name, salary, department):
        super().__init__(name, salary)
        self.department = department

    def display(self):
        return f"{super().display()}, Department: {self.department}"

m = Manager("Amit", 75000, "IT")
print(m.display())
# Output: Name: Amit, Salary: 75000, Department: IT
print(isinstance(m, Employee))  # True

Types of Inheritance — Comparison

Type Parents Example Use Case
Single One parent class B(A) Most common
Multiple Two or more parents class C(A, B) Mixing behaviors
Multilevel Chain (grandparent→parent→child) class C(B) where B(A) Hierarchical layers
Hierarchical One parent, many children class B(A), class C(A) Shared base

Common Mistakes

  • Forgetting to call super().__init__() — parent constructor won't execute.
  • Calling super() before defining the class — causes error.
  • Using self inside super()super() does not take self in Python 3.
  • Confusing isinstance() with issubclass() — check docs for both.

University Exam Tip

University exams often ask: "Explain types of inheritance with example" or "What is method overriding?". Use diagrams for each type, write a short definition, and include a 5–6 line code example. Always mention super() and isinstance().

Key Points

Inheritance enables code reuse and establishes an "is-a" relationship.

Python supports single, multiple, multilevel, and hierarchical inheritance.

super() is used to call parent class methods from the child class.

Method overriding lets a child redefine a parent method with the same name.

MRO (Method Resolution Order) determines method lookup in multiple inheritance.

isinstance(obj, ClassName) checks if an object belongs to a class.

Every Python class implicitly inherits from the object class.

Draw inheritance diagrams in exams for extra clarity.

Practice Questions

  1. Write a program to create a BankAccount class and a child class SavingsAccount with interest calculation.
  2. Explain multiple inheritance with a real-world example (e.g., SmartPhone inheriting from Camera and Phone).
  3. What is MRO? Demonstrate with a 3-level inheritance chain.
  4. Write a program using super() to initialize parent class attributes in a child class.
  5. Difference between method overriding and method overloading with examples.

Summary

Inheritance is one of the most important OOP concepts in Python. It supports code reusability, logical structuring, and real-world modeling. Master the four types, super(), method overriding, and MRO for exams and interviews.

Python Programming Handwritten Notes

Master Python Programming with Easy Handwritten Notes – Perfect for Interviews, Placements, GATE & Exams.