Skip to content

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

Inheritance

Creating a class that extends another: the 'is-a' relationship, inheriting attributes and methods, adding new behaviour, super(), isinstance with subclasses, and when composition is better.

Beginner 12 min read·Lesson 172 of 306 in Python Programming

Learning objectives

  • Create subclasses that reuse parent code
  • Extend parent behaviour with super()
  • Recognise genuine is-a relationships

Definition

Inheritance lets a new class (the subclass or child) be defined in terms of an existing class (the superclass or parent). The subclass inherits the parent's methods and attributes and can add new ones or override existing ones.

Introduction

A SavingsAccount is an Account that also earns interest. Instead of copying Account's code, the subclass inherits it and adds only what's different.

Why it matters

Inheritance removes duplication across related types and lets code that works with the parent also work with every child — the basis of polymorphism.

Detailed explanation

Syntax: class Child(Parent): ... The child gets all of the parent's methods and class attributes.

Every class implicitly inherits from object, which provides default __str__, __eq__ and other methods.

A subclass can add new methods and attributes, and override parent methods by defining a method with the same name.

super() gives access to the parent's version: super().__init__(...) runs the parent's initialisation, super().describe() reuses its behaviour.

isinstance(obj, Parent) is True for instances of subclasses too; issubclass(Child, Parent) checks the relationship between classes.

Use inheritance only for true 'is-a' relationships. If a class merely uses another (a Car has an Engine), use composition instead.

Syntax

Python
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def describe(self):
return f"{self.owner}: {self.balance}"
class SavingsAccount(Account):
def __init__(self, owner, balance=0, rate=0.04):
super().__init__(owner, balance)
self.rate = rate
def describe(self):
return super().describe() + f" @ {self.rate:.0%}"
  • class Child(Parent):
  • super() reaches the parent's methods.
  • Subclass instances are also parent instances.

Code examples

Inheriting methods

Python
class Animal:
def __init__(self, name):
self.name = name
def describe(self):
return f"{self.name} is an animal"
class Dog(Animal):
def fetch(self):
return f"{self.name} fetches the ball"
d = Dog("Bruno")
print(d.describe())
print(d.fetch())
print(isinstance(d, Animal), issubclass(Dog, Animal), issubclass(Dog, object))
Output
Bruno is an animal
Bruno fetches the ball
True True True

Extending with super()

Python
class Account:
def __init__(self, owner, balance=0):
self.owner, self.balance = owner, balance
def describe(self):
return f"{self.owner}: {self.balance}"
class SavingsAccount(Account):
def __init__(self, owner, balance=0, rate=0.04):
super().__init__(owner, balance)
self.rate = rate
def describe(self):
return super().describe() + f" @ {self.rate:.0%}"
print(SavingsAccount("Asha", 12000).describe())
Output
Asha: 12000 @ 4%

More examples

One function, many subclasses

Python
class Employee:
def __init__(self, name, base):
self.name, self.base = name, base
def monthly_pay(self):
return self.base
class Manager(Employee):
def __init__(self, name, base, team_size):
super().__init__(name, base)
self.team_size = team_size
def monthly_pay(self):
return super().monthly_pay() + 1000 * self.team_size
class Intern(Employee):
def monthly_pay(self):
return round(super().monthly_pay() * 0.5)
staff = [Employee("Ravi", 40000), Manager("Asha", 70000, 5), Intern("Meera", 30000)]
for e in staff:
print(f"{e.name:<6}{type(e).__name__:<9}{e.monthly_pay():>7}")
print("payroll:", sum(e.monthly_pay() for e in staff))
Output
Ravi  Employee   40000
Asha  Manager    75000
Meera Intern     15000
payroll: 130000

Step-by-step explanation

  • Manager adds a team_size attribute and extends monthly_pay with super().
  • Intern doesn't define __init__, so it inherits Employee's constructor.
  • The loop calls monthly_pay on every object without checking its type; each class supplies its own rule.

Expected output

Running “One function, many subclasses” prints exactly:

TextOutput
Ravi Employee 40000
Asha Manager 75000
Meera Intern 15000
payroll: 130000

Practical applications

  • Exception classes form a big inheritance tree.
  • Frameworks ask you to subclass their base classes (Django's View, unittest.TestCase).

Best practices

  • Keep hierarchies shallow (two or three levels).
  • Use super() to extend parent behaviour.
  • Prefer composition unless the is-a relationship is genuine.

Common mistakes

Inheritance for code reuse only

Avoid

class Car(Engine): ... # a car is not an engine

Prefer

class Car:
def __init__(self):
self.engine = Engine()

Use composition when the relationship is has-a.

Calling the parent method by name

Avoid

Account.__init__(self, owner) # works, but breaks with multiple inheritance

Prefer

super().__init__(owner)

super() follows the method resolution order correctly.

Important notes

  • The following lessons look at single, multiple and multilevel inheritance in more detail.

Key takeaways

  • class Child(Parent) reuses the parent's code.
  • Subclasses can add and override methods; super() reaches the parent.
  • Inheritance models is-a; composition models has-a.

Try it yourself

  1. 1
    Create Vehicle, Car and Bike classes where each subclass overrides wheels() and description().
  2. 2
    Add a Contractor subclass to the Employee example with an hourly pay rule.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
Practise this topic