Course topics

By WebNest Studio Engineering Team

Python Tutorial

Inheritance in Python

Inheritance lets a new class reuse and extend an existing one. A SavingsAccount is a BankAccount with interest; an Admin is a User with extra permissions. The new class (child, subclass) inherits the attributes and methods of the existing class (parent, base, superclass) and can add or override behaviour.

This lesson covers single, multilevel, hierarchical and multiple inheritance, super(), method overriding, the Method Resolution Order (MRO), isinstance/issubclass, and mixins.

Why it matters

Inheritance lets a new class reuse an existing one and change only what differs. Frameworks depend on it: you write a Django model by inheriting from Model, an exception by inheriting from Exception, a test case by inheriting from TestCase. Understanding super() and the method resolution order is what makes those work as expected.

Single Inheritance and Overriding

class Child(Parent): creates a subclass. The child inherits everything; defining a method with the same name overrides the parent's. Inside the override, super().method() calls the parent version so you extend rather than replace behaviour. Every class ultimately inherits from object.

Types of Inheritance

The common structures:

  • Single — one parent: Dog(Animal).
  • Multilevel — a chain: Puppy(Dog), Dog(Animal).
  • Hierarchical — several children of one parent: Dog(Animal), Cat(Animal).
  • Multiple — several parents: FlyingCar(Car, Aircraft).
  • Hybrid — a combination of the above.

Multiple Inheritance and the MRO

With several parents, Python searches for attributes in the Method Resolution Order, computed by the C3 linearisation algorithm and visible in Class.__mro__ or Class.mro(). super() follows the MRO, not simply "the parent", which lets cooperative classes each run once even in diamond-shaped hierarchies.

Mixins

A mixin is a small class that adds one capability (serialisation to JSON, logging, comparison) and is designed to be combined with others through multiple inheritance: class Order(JsonMixin, TimestampMixin, Model). Mixins should not have their own __init__ state requirements.

Examples

Single inheritance, overriding and super()

Python
class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner, self.balance = owner, balance

    def describe(self):
        return f"{self.owner}: Rs.{self.balance}"

    def month_end(self):
        pass

class SavingsAccount(BankAccount):
    def __init__(self, owner, balance=0, rate=0.04):
        super().__init__(owner, balance)
        self.rate = rate

    def month_end(self):                       # override
        self.balance += round(self.balance * self.rate / 12, 2)

    def describe(self):                        # extend
        return super().describe() + f" (savings @ {self.rate:.0%})"

acc = SavingsAccount("Asha", 12000)
acc.month_end()
print(acc.describe())
print(isinstance(acc, BankAccount), issubclass(SavingsAccount, BankAccount))
Output
Asha: Rs.12040.0 (savings @ 4%)
True True

Multilevel and hierarchical inheritance

Python
class Animal:
    def __init__(self, name):
        self.name = name
    def speak(self):
        return "..."
    def intro(self):
        return f"{self.name} says {self.speak()}"

class Dog(Animal):
    def speak(self):
        return "Woof"

class Puppy(Dog):
    def speak(self):
        return super().speak() + " (tiny)"

class Cat(Animal):
    def speak(self):
        return "Meow"

for pet in [Dog("Rex"), Puppy("Bolt"), Cat("Tom"), Animal("Generic")]:
    print(pet.intro())
print([c.__name__ for c in Puppy.__mro__])
Output
Rex says Woof
Bolt says Woof (tiny)
Tom says Meow
Generic says ...
['Puppy', 'Dog', 'Animal', 'object']

Multiple inheritance, the diamond and the MRO

Python
class Base:
    def setup(self):
        print("Base.setup")

class Logging(Base):
    def setup(self):
        print("Logging.setup")
        super().setup()

class Caching(Base):
    def setup(self):
        print("Caching.setup")
        super().setup()

class Service(Logging, Caching):
    def setup(self):
        print("Service.setup")
        super().setup()

Service().setup()
print([c.__name__ for c in Service.mro()])
Output
Service.setup
Logging.setup
Caching.setup
Base.setup
['Service', 'Logging', 'Caching', 'Base', 'object']

A mixin adding JSON serialisation

Python
import json

class JsonMixin:
    def to_json(self):
        return json.dumps(vars(self), sort_keys=True)

class Course:
    def __init__(self, title, lessons):
        self.title, self.lessons = title, lessons

class PublishedCourse(JsonMixin, Course):
    pass

print(PublishedCourse("Python", 130).to_json())
Output
{"lessons": 130, "title": "Python"}

Common Mistakes

  • Forgetting to call super().__init__() in a subclass constructor.
  • Calling Parent.method(self) directly in multiple inheritance, which can run a base class twice; use super().
  • Deep inheritance hierarchies that are hard to follow — prefer composition for "has-a" relationships.
  • Inheriting just to reuse one helper method.

Exercise

Employee is given. Write Manager, which inherits from it, takes an extra bonus, and overrides pay to return the salary plus the bonus, reusing the parent's method. Then print the names of the classes in the method resolution order of Manager.

Expected output: 60000 then ['Manager', 'Employee', 'object']

Python · starter code
class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def pay(self):
        return self.salary


# TODO: class Manager(Employee) with a bonus and an overridden pay()


print(Manager("Asha", 50000, 10000).pay())
print([cls.__name__ for cls in Manager.__mro__])
Show hints
  • Call super().__init__(name, salary) so the parent stores the name and salary.
  • In pay, return super().pay() + self.bonus.
Show solution
Python · solution
class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def pay(self):
        return self.salary


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

    def pay(self):
        return super().pay() + self.bonus


print(Manager("Asha", 50000, 10000).pay())
print([cls.__name__ for cls in Manager.__mro__])

Quick quiz

1. Does Python support multiple inheritance?

  • A. No
  • B. Yes; a class can list several parent classes
  • C. Only for abstract classes
  • D. Only through mixins
Show answer

B. For example, class C(A, B). The order of the parents matters.

2. What is the MRO?

  • A. The order in which objects are created
  • B. A memory optimisation
  • C. The order in which classes are searched for a method or attribute
  • D. The list of a module's imports
Show answer

C. It can be inspected with ClassName.__mro__.

3. A subclass defines a method with the same name as one in its parent. Which runs when it is called on a subclass object?

  • A. The subclass's
  • B. The parent's
  • C. Both, parent first
  • D. It raises an error
Show answer

A. This is overriding. The parent's version is still reachable through super().

Interview questions

What is the method resolution order and how does Python handle the diamond problem?

Show answer

The MRO is the order in which Python searches classes when looking up a method. With multiple inheritance, two parents may share a common ancestor, forming a diamond. Python builds a single linear order using the C3 algorithm: a class comes before its parents, parents keep the order in which they were listed, and each class appears once. super() follows this order, so the shared ancestor's method runs only once.

What is a mixin?

Show answer

A mixin is a small class that provides one piece of behaviour, such as converting to JSON or logging, and is meant to be combined with other classes through multiple inheritance. It is not intended to be instantiated on its own and usually has no state. Mixins allow a feature to be shared between classes that are otherwise unrelated.

Key Points to Remember

  • class Child(Parent) inherits attributes and methods; overriding replaces them.
  • super() calls the next class in the MRO, letting you extend behaviour.
  • Python supports single, multilevel, hierarchical, multiple and hybrid inheritance.
  • The MRO (Class.__mro__) defines lookup order in multiple inheritance.
  • Mixins add focused capabilities through multiple inheritance.

Practice in the playground

Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.

Run the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.

WebNest Studio

Written by

WebNest Studio Engineering Team

Practical lessons from developers working with Java, Python, React, databases and production systems.

Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering