Chapter 47 of 54

Inheritance in Python

Imagine you are building a college management system. Students, teachers and staff all have a name, an age and contact details. Writing the same attributes and methods in three separate classes would mean repeating code, and fixing a bug three times.

Inheritance lets you write the common parts once in a general class and then create specialised classes that automatically get all of it, while adding or changing only what is different. It is one of the four pillars of OOP and builds directly on the classes you learned in the previous chapter.

What is Inheritance?

Inheritance is a mechanism where a new class (the child or subclass) acquires the attributes and methods of an existing class (the parent, base or superclass).

Inheritance models an "is-a" relationship:

        Animal            (parent / base class)
       /      \
     Dog      Cat         (children / subclasses)

A Dog IS AN Animal.   A Cat IS AN Animal.

Everything an Animal can do, a Dog can also do, plus its own extra abilities.


Basic Syntax

Put the parent class name in brackets after the child class name:

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

    def eat(self):
        print(f"{self.name} is eating")

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

class Dog(Animal):
    def fetch(self):
        print(f"{self.name} is fetching the ball")

d = Dog("Bruno")
d.eat()
d.speak()
d.fetch()

Output:

Bruno is eating
Bruno makes a sound
Bruno is fetching the ball

Dog did not define __init__, eat() or speak(), yet it can use them all. When you call d.eat(), Python looks for eat in Dog first; it isn't there, so Python moves up to Animal and finds it.


Method Overriding

A child class can provide its own version of a parent's method. This is called overriding.

class Cat(Animal):
    def speak(self):
        print(f"{self.name} says Meow")

c = Cat("Kitty")
c.speak()
Animal("Generic").speak()

Output:

Kitty says Meow
Generic makes a sound

Python uses the closest definition. Cat has its own speak(), so that one runs. The parent's version is unchanged for other objects.


The super() Function

Often you don't want to replace the parent's method completely, only extend it. super() gives you access to the parent class's version.

The most common case is __init__. A Student needs everything a Person has, plus a branch:

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

    def details(self):
        return f"{self.name}, {self.age} years"

class Student(Person):
    def __init__(self, name, age, branch):
        super().__init__(name, age)    # let Person set name and age
        self.branch = branch           # then add the new attribute

    def details(self):
        return super().details() + f", {self.branch}"

s = Student("Asha", 20, "CSE")
print(s.details())

Output:

Asha, 20 years, CSE

Step by step:

  1. Student("Asha", 20, "CSE") calls Student.__init__.

  2. super().__init__(name, age) runs Person.__init__ on the same object, setting self.name and self.age.

  3. self.branch = branch adds the student-specific attribute.

  4. s.details() runs Student.details, which reuses Person.details and appends the branch.

What happens if you forget super().__init__()?

class BadStudent(Person):
    def __init__(self, name, age, branch):
        self.branch = branch       # forgot super().__init__

b = BadStudent("Ravi", 21, "IT")
print(b.details())

This raises:

AttributeError: 'BadStudent' object has no attribute 'name'

Defining __init__ in the child replaces the parent's __init__, so Person.__init__ never ran and name was never set.


Checking Relationships: isinstance() and issubclass()

print(isinstance(s, Student))
print(isinstance(s, Person))
print(isinstance(Person("X", 1), Student))
print(issubclass(Student, Person))
print(issubclass(Person, object))

Output:

True
True
False
True
True

A Student object is also a Person, but a Person is not necessarily a Student. The last line shows that every class in Python ultimately inherits from the built-in object class, even if you don't write it.


Types of Inheritance

1. Single inheritance

One child, one parent, like Dog(Animal) above.

2. Multilevel inheritance

A chain: grandparent, parent, child.

class Vehicle:
    def start(self):
        print("Vehicle started")

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

class ElectricCar(Car):
    def charge(self):
        print("Charging battery")

e = ElectricCar()
e.start()
e.drive()
e.charge()

Output:

Vehicle started
Car is driving
Charging battery

3. Hierarchical inheritance

Several children share one parent:

class Shape:
    def __init__(self, name):
        self.name = name

    def area(self):
        return 0

class Rectangle(Shape):
    def __init__(self, w, h):
        super().__init__("Rectangle")
        self.w = w
        self.h = h

    def area(self):
        return self.w * self.h

class Circle(Shape):
    def __init__(self, r):
        super().__init__("Circle")
        self.r = r

    def area(self):
        return round(3.14159 * self.r ** 2, 2)

for sh in [Rectangle(4, 5), Circle(3)]:
    print(sh.name, sh.area())

Output:

Rectangle 20
Circle 28.27

The loop calls area() without caring which shape it has. Each object runs its own version. This idea is called polymorphism, the topic of the next chapter.

4. Multiple inheritance

Unlike Java, Python allows a class to inherit from more than one parent:

class Camera:
    def take_photo(self):
        print("Photo taken")

class Phone:
    def call(self, number):
        print(f"Calling {number}")

class Smartphone(Phone, Camera):
    pass

sp = Smartphone()
sp.call("98765 43210")
sp.take_photo()

Output:

Calling 98765 43210
Photo taken
TypeStructureExample
SingleA → BDog(Animal)
MultilevelA → B → CElectricCar(Car), Car(Vehicle)
HierarchicalA → B, A → CRectangle(Shape), Circle(Shape)
MultipleA, B → CSmartphone(Phone, Camera)
HybridA mix of the aboveThe diamond below

Method Resolution Order (MRO)

With multiple inheritance, what if two parents have a method with the same name? This is the famous diamond problem:

        A
       / \
      B   C
       \ /
        D
class A:
    def hello(self):
        print("Hello from A")

class B(A):
    def hello(self):
        print("Hello from B")

class C(A):
    def hello(self):
        print("Hello from C")

class D(B, C):
    pass

D().hello()
print([cls.__name__ for cls in D.__mro__])

Output:

Hello from B
['D', 'B', 'C', 'A', 'object']

Python decides using the Method Resolution Order, computed by an algorithm called C3 linearization. You can see it with ClassName.__mro__ or ClassName.mro(). Python searches the classes in that order and uses the first match. The rough rules: a child comes before its parents, and parents are checked in the order you listed them (B before C), and a shared parent like A appears only once, after all its children.

This is also why super() does not simply mean "my parent". It means "the next class in the MRO". When every class calls super(), each method in the chain runs exactly once:

class A:
    def hello(self):
        print("A")

class B(A):
    def hello(self):
        print("B")
        super().hello()

class C(A):
    def hello(self):
        print("C")
        super().hello()

class D(B, C):
    def hello(self):
        print("D")
        super().hello()

D().hello()

Output:

D
B
C
A

Notice that super() inside B called C, not A, because C comes after B in D's MRO.


Inheritance You Already Used

In the Exception Handling chapter, you created custom exceptions like class InsufficientBalanceError(Exception). That was inheritance! Your class inherited everything that makes an exception work. You can even inherit from a more specific exception, so existing handlers still catch it:

class InvalidMarksError(ValueError):
    pass

try:
    raise InvalidMarksError("Marks must be 0-100")
except ValueError as e:
    print(type(e).__name__, "->", e)

Output:

InvalidMarksError -> Marks must be 0-100

Common Mistakes

  • Forgetting super().__init__() in a child's __init__, so parent attributes are never created.

  • Passing self to super(): write super().__init__(name), not super().__init__(self, name).

  • Misspelling an overridden method. If the child defines spaek() instead of speak(), Python silently uses the parent's version.

  • Using inheritance for "has-a" relationships. A Car has an Engine; it is not an engine. Store an Engine object as an attribute instead (this is called composition).

  • Building very deep hierarchies. Long chains are hard to follow. Prefer shallow trees and composition where possible.


Summary

  • Inheritance lets a child class reuse the attributes and methods of a parent: class Child(Parent):.

  • A child can add new methods and override existing ones.

  • super() calls the next class's version, most often super().__init__(...).

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

  • The MRO (Class.__mro__) decides which method runs when names clash.

Use inheritance for genuine "is-a" relationships to reuse code, and use super() to build on the parent instead of repeating it.

Interview tips: Know that Python supports multiple inheritance (Java does not for classes), be able to explain the diamond problem and MRO, and know the difference between overriding (same method name in the child) and overloading (Python does not support traditional overloading; the last definition with a given name wins, so use default arguments instead).

Practice: Create an Employee class with name and salary, then a Manager subclass that adds a team list and overrides a show() method using super().