Skip to content

Module 11 · Object-Oriented Programming — topic 18 of 25

Multilevel inheritance

Chains of inheritance — grandparent, parent, child: how attributes flow down the chain, extending behaviour at each level with super(), and keeping hierarchies shallow.

Beginner 8 min read·Lesson 175 of 306 in Python Programming

Learning objectives

  • Build a three-level class chain
  • Extend behaviour at each level with super()
  • Recognise when a chain is too deep

Definition

Multilevel inheritance is when a class inherits from a class that itself inherits from another class, forming a chain such as Vehicle → Car → ElectricCar. The child gets everything from every level above it.

Introduction

An ElectricCar is a Car, and a Car is a Vehicle, so an ElectricCar is also a Vehicle. Each level adds a little more detail to the one above it.

Why it matters

Multilevel chains appear everywhere in real libraries — Python's own exception tree is one. Knowing how they behave helps you read and extend such code.

Detailed explanation

In class C(B) where class B(A), objects of C have the methods of C, B and A; lookup goes C → B → A → object.

The is-a relationship is transitive: isinstance(c, A) is True.

Each level's __init__ should call super().__init__(...) with the arguments the level above needs, then add its own attributes.

Methods can be extended at every level: each override calls super().method() and adds its part, building the result up the chain.

Deep chains (four, five or more levels) are hard to understand because behaviour is spread across many files. Two or three levels is usually enough.

Syntax

Python
class Vehicle:
...
class Car(Vehicle):
...
class ElectricCar(Car):
...
print(ElectricCar.__mro__)
  • Each class has one parent.
  • The child inherits from all levels.
  • Call super() at every level.

Code examples

Building up a description

Python
class Vehicle:
def __init__(self, brand):
self.brand = brand
def info(self):
return self.brand
class Car(Vehicle):
def __init__(self, brand, seats):
super().__init__(brand)
self.seats = seats
def info(self):
return super().info() + f", {self.seats} seats"
class ElectricCar(Car):
def __init__(self, brand, seats, range_km):
super().__init__(brand, seats)
self.range_km = range_km
def info(self):
return super().info() + f", {self.range_km} km range"
e = ElectricCar("Tata", 5, 315)
print(e.info())
print([c.__name__ for c in ElectricCar.__mro__])
print(isinstance(e, Vehicle))
Output
Tata, 5 seats, 315 km range
['ElectricCar', 'Car', 'Vehicle', 'object']
True

Attributes flow down the chain

Python
class A:
x = "from A"
class B(A):
pass
class C(B):
y = "from C"
print(C.x, "|", C.y)
print(hasattr(B, "y"))
Output
from A | from C
False

More examples

An exception hierarchy

Python
class AppError(Exception):
pass
class PaymentError(AppError):
pass
class CardDeclined(PaymentError):
def __init__(self, last4):
super().__init__(f"card ending {last4} declined")
self.last4 = last4
def pay(card):
if card.endswith("0000"):
raise CardDeclined(card[-4:])
return "paid"
for card in ["4111111111111111", "4000000000000000"]:
try:
print(pay(card))
except PaymentError as e:
print("payment problem:", e, "|", type(e).__name__)
print([c.__name__ for c in CardDeclined.__mro__])
Output
paid
payment problem: card ending 0000 declined | CardDeclined
['CardDeclined', 'PaymentError', 'AppError', 'Exception', 'BaseException', 'object']

Step-by-step explanation

  • CardDeclined is three levels below Exception in our own code, and five levels above object overall.
  • except PaymentError catches CardDeclined because a CardDeclined is a PaymentError.
  • The MRO shows the full chain, including Python's built-in BaseException.

Expected output

Running “An exception hierarchy” prints exactly:

TextOutput
paid
payment problem: card ending 0000 declined | CardDeclined
['CardDeclined', 'PaymentError', 'AppError', 'Exception', 'BaseException', 'object']

Practical applications

  • Python's exceptions: FileNotFoundError → OSError → Exception → BaseException.
  • GUI toolkits: Button → Widget → Object.

Best practices

  • Keep chains to two or three levels.
  • Call super() in every overridden __init__ and method you extend.
  • Catch exceptions at the level of the hierarchy you can actually handle.

Common mistakes

Skipping a level's initialisation

Avoid

class ElectricCar(Car):
def __init__(self, brand, seats, range_km):
self.range_km = range_km # no super()

Prefer

super().__init__(brand, seats)
self.range_km = range_km

Without super(), brand and seats never get set.

Important notes

  • Multilevel and multiple inheritance can be combined, which is when reading __mro__ becomes essential.

Key takeaways

  • Multilevel inheritance forms a chain of classes.
  • Children inherit from every ancestor.
  • Use super() at each level and keep the chain short.

Try it yourself

  1. 1
    Create Account → SavingsAccount → FixedDeposit with a describe method extended at each level.
  2. 2
    Print the MRO of FileNotFoundError and explain each step.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

16 questions cover the “Object-Oriented Programming” module. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
  • ModerateWhat is printed?
  • ModerateWhat is printed?
Practise this module