Python Inheritance
Inheritance is one of OOP's most powerful pillars — it lets a child
class acquire all the attributes and methods of a parent class, then extend or specialise them. Instead of
copying code, you write it once and reuse it through the hierarchy. This chapter covers single
inheritance, multi-level inheritance, multiple inheritance, the
critical super() function, method overriding, and
Python's MRO (Method Resolution Order) — with clear responsive diagrams that work on any
screen size.
What is Inheritance?
Inheritance allows a child class (also called subclass or derived class) to automatically receive all the attributes and methods of a parent class (also called superclass or base class). The child can use everything the parent has, and can also add new things or change existing behaviour.
Single Inheritance
The simplest form — one child class inherits from exactly one parent class. Syntax:
class Child(Parent):. The child automatically has access to every
attribute and method of the parent.
+ __init__(name, sound)
+ speak() → "{name} says {sound}"
+ describe() → "I am {name}"
+ __init__(name, breed)
+ fetch() → "{name} fetches!" (new)
✓ inherits: speak(), describe()
# ── Parent class ─────────────────────────────────────
class Animal:
def __init__(self, name, sound):
self.name = name
self.sound = sound
def speak(self):
return f"{self.name} says {self.sound}!"
def describe(self):
return f"I am {self.name}"
# ── Child class — inherits from Animal ───────────────
class Dog(Animal): # ← Dog IS-A Animal
def __init__(self, name, breed):
super().__init__(name, sound="Woof") # call parent __init__
self.breed = breed # new attribute
def fetch(self): # new method
return f"{self.name} fetches the ball!"
# Create objects
generic = Animal("Cat", "Meow")
rex = Dog("Rex", "Labrador")
# Inherited methods work on child
print(rex.speak()) # Rex says Woof! ← inherited from Animal
print(rex.describe()) # I am Rex ← inherited
print(rex.fetch()) # Rex fetches… ← Dog's own method
print(rex.breed) # Labrador
# Type checking
print(isinstance(rex, Dog)) # True
print(isinstance(rex, Animal)) # True ← Dog IS-A Animal!
print(issubclass(Dog, Animal)) # True
Multi-Level Inheritance
A chain of inheritance where a class inherits from a child, which already inherits from a parent: Grandparent → Parent → Child. Each level adds to or specialises the one above it.
+ start() → "Engine starts"
+ info() → make + year
+ honk() → "Beep!" (new)
✓ start(), info()
+ charge() (new)
+ start() overridden (override)
✓ honk(), info()
class Vehicle:
def __init__(self, make, year):
self.make = make
self.year = year
def start(self):
return f"{self.make} engine starts"
def info(self):
return f"{self.year} {self.make}"
class Car(Vehicle):
def __init__(self, make, year, doors=4):
super().__init__(make, year)
self.doors = doors
def honk(self):
return "Beep!"
class ElectricCar(Car): # inherits from Car (which inherits from Vehicle)
def __init__(self, make, year, battery_range):
super().__init__(make, year)
self.battery_range = battery_range
def charge(self):
return f"Charging… {self.battery_range}km range"
def start(self): # OVERRIDE Vehicle.start()
return f"{self.make} silently starts (electric)"
tesla = ElectricCar("Tesla", 2025, 500)
print(tesla.info()) # 2025 Tesla ← Vehicle method
print(tesla.honk()) # Beep! ← Car method
print(tesla.start()) # Tesla silently… ← overridden
print(tesla.charge()) # Charging… 500km ← ElectricCar method
print(isinstance(tesla, ElectricCar)) # True
print(isinstance(tesla, Vehicle)) # True — transitive!
super() — Calling Parent Methods
super() returns a proxy object that lets you call
methods from the parent class without explicitly naming it. This is the correct, future-proof way to extend
parent behaviour — it works correctly with multiple inheritance and MRO.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
return f"Hi, I'm {self.name}, {self.age} years old"
class Employee(Person):
def __init__(self, name, age, company, salary):
super().__init__(name, age) # ✅ extend parent __init__
self.company = company # add new attrs
self.salary = salary
def introduce(self):
base = super().introduce() # ✅ extend parent method
return f"{base}. I work at {self.company}."
class Manager(Employee):
def __init__(self, name, age, company, salary, team_size):
super().__init__(name, age, company, salary)
self.team_size = team_size
def introduce(self):
base = super().introduce()
return f"{base} I manage {self.team_size} people."
m = Manager("Alice", 35, "K2infocom", 100000, 12)
print(m.introduce())
# Hi, I'm Alice, 35 years old. I work at K2infocom. I manage 12 people.
# super() vs explicit parent name
# super().__init__(...) ← ✅ recommended — MRO-aware
# Person.__init__(self, ...) ← works but breaks with multiple inheritance
Parent.__init__(self, ...) breaks as soon as you introduce multiple
inheritance. super() is MRO-aware and always calls the next class in the
correct order.
Method Overriding
Method overriding is when a child class defines a method with the
same name as one in the parent. Python always uses the most specific (child) version. You can still
access the parent's version via super().
class Shape:
def area(self):
return 0
def describe(self):
return f"I am a shape with area {self.area():.2f}"
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self): # OVERRIDES Shape.area()
import math
return math.pi * self.radius ** 2
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self): # OVERRIDES Shape.area()
return self.width * self.height
class Square(Rectangle):
def __init__(self, side):
super().__init__(side, side) # reuse Rectangle.__init__
# describe() uses the overridden area() automatically!
shapes = [Shape(), Circle(5), Rectangle(4,6), Square(3)]
for s in shapes:
print(s.describe())
# I am a shape with area 0.00
# I am a shape with area 78.54
# I am a shape with area 24.00
# I am a shape with area 9.00
Multiple Inheritance
Python allows a class to inherit from two or more parent classes. The child gets all attributes and methods from every parent. This is powerful but can lead to the "Diamond Problem" — resolved by Python's MRO algorithm.
✓ fly() from Flyable
✓ swim() from Swimmable
class Flyable:
def fly(self):
return "I can fly!"
class Swimmable:
def swim(self):
return "I can swim!"
# Duck inherits from BOTH parents
class Duck(Flyable, Swimmable):
def quack(self):
return "Quack!"
d = Duck()
print(d.fly()) # I can fly! ← from Flyable
print(d.swim()) # I can swim! ← from Swimmable
print(d.quack()) # Quack! ← Duck's own
# Real-world: Mixins — composable behaviour slices
class LogMixin:
"""Adds logging to any class."""
def log(self, message):
print(f"[{self.__class__.__name__}] {message}")
class JsonMixin:
"""Adds JSON serialisation to any class."""
def to_json(self):
import json
return json.dumps(self.__dict__)
class User(LogMixin, JsonMixin):
def __init__(self, name, email):
self.name = name
self.email = email
u = User("Alice", "alice@example.com")
u.log("Created") # [User] Created
print(u.to_json()) # {"name": "Alice", "email": "alice@example.com"}
MRO — Method Resolution Order
When multiple parents define the same method name, Python uses the MRO
(C3 linearisation algorithm) to decide which version to call. The MRO is the order Python searches through the
class hierarchy — from most specific (the class itself) to most general (object).
Python searches left to right — stops at the first class that defines the method
class A:
def hello(self):
return "Hello from A"
class B(A):
def hello(self):
return "Hello from B"
class C(A):
def hello(self):
return "Hello from C"
class D(B, C): # inherits from B first, then C
pass
d = D()
print(d.hello()) # "Hello from B" ← B is searched before C
# Inspect the MRO
print(D.mro())
# [D, B, C, A, object]
print(D.__mro__) # tuple version
# super() follows the MRO — not just one level up
class E(B, C):
def hello(self):
return super().hello() + " → via E"
print(E().hello()) # Hello from B → via E
# isinstance and issubclass work through the entire chain
print(issubclass(D, A)) # True
print(issubclass(D, B)) # True
print(issubclass(D, C)) # True
object — it's always the
last entry in any MRO. object provides default implementations of __str__, __repr__, __eq__, and others.
Practice Python Online — Free Compilers
Don't want to install anything yet? Practice all inheritance examples from this chapter directly in your browser with these free Python environments.
- Inheritance lets a child class acquire all attributes and methods of a parent class using
class Child(Parent):. - Single inheritance — one parent. Multi-level — a chain (Grandparent →
Parent → Child). Multiple inheritance — two or more parents:
class Child(A, B):. super()calls the next class in the MRO — always use it instead of hardcoding the parent name.super().__init__()extends the parent constructor.- Method overriding — redefine an inherited method in the child class. Python always uses
the most specific (child) version. Call
super().method()to also run the parent's version. - Every class ultimately inherits from
object. Useisinstance(obj, Class)andissubclass(Child, Parent)to check relationships. - The MRO (Method Resolution Order) defines the exact order Python searches when looking up
a method. Inspect it with
ClassName.mro()orClassName.__mro__. - Mixins are small reusable classes with a single responsibility (logging, JSON serialisation, etc.) mixed into other classes via multiple inheritance.
- Use inheritance when a clear IS-A relationship exists. Prefer composition (has-a) over deep inheritance hierarchies for flexibility.
super() returns a proxy object that lets you call methods from
the next class in the MRO. In simple single inheritance this means the immediate
parent, but with multiple inheritance it correctly follows the full MRO order.
The key use cases are: calling the parent's __init__ to initialise parent attributes, and extending (rather than
fully replacing) an inherited method.
class Child(Parent):
def __init__(self, x, y):
super().__init__(x) # ← runs Parent.__init__
self.y = y # ← add child-specific attr
Method overriding occurs when a child class defines a method with the same name as one inherited from a parent. Python always uses the most specific version — the child's version.
You can still access the parent's version by calling super().method_name(). This is how you extend rather than
replace parent behaviour.
Method overriding is the basis of polymorphism — different classes can provide their own specific implementations of the same method interface.
MRO (Method Resolution Order) is the order in which Python searches through the class hierarchy to find a method. Python uses the C3 linearisation algorithm to compute it.
It matters for multiple inheritance because when two parent classes both
define the same method, the MRO determines which one Python uses. Inspect with ClassName.mro().
class D(B, C): pass
print(D.mro()) # [D, B, C, A, object]
# Python searches this order for any method lookup
A mixin is a small class with a single, focused responsibility that is designed to be "mixed in" to other classes via multiple inheritance. Mixins do not stand alone — they add capability to other classes without becoming a true parent.
Use mixins when you want to add the same behaviour to several unrelated classes without creating a deep inheritance chain. Common examples: logging, JSON serialisation, timestamping, caching, authentication checks.
class LogMixin:
def log(self, msg): print(f"[{self.__class__.__name__}] {msg}")
class User(LogMixin, BaseModel): pass # gets logging for free
isinstance(obj, Class) checks if an object is an
instance of Class or any of its subclasses — it works on an
instance.
issubclass(Child, Parent) checks if a
class is a subclass of another class — it works on the class itself.
rex = Dog("Rex")
isinstance(rex, Dog) # True — rex IS a Dog
isinstance(rex, Animal) # True — Dog IS-A Animal
issubclass(Dog, Animal) # True — class check
Dog
that inherits from Animal?class D(B, C): what does D.mro() return (assuming B and C both inherit A)?