Reading history

Python Inheritance: super(), Overriding and MRO

4 min read 1 views

Learn Python inheritance: creating subclasses, super(), method overriding, multiple inheritance, the method resolution order and isinstance().

Inheritance lets a new class take everything an existing class has and then add or change parts of it. A Car is a kind of Vehicle, so rather than rewriting the shared code, Car inherits it. The existing class is the parent (base class) and the new one is the child (subclass). This lesson covers single and multiple inheritance, super(), method overriding and the method resolution order.

In this lesson you will learn

  • How to create a subclass
  • How super() calls the parent’s code
  • How to override a parent method
  • How multiple inheritance works and what the MRO is
  • isinstance() and issubclass()

Single Inheritance, super() and Overriding

class Vehicle:
    def __init__(self, brand, wheels):
        self.brand = brand
        self.wheels = wheels

    def describe(self):
        return f"{self.brand} with {self.wheels} wheels"

class Car(Vehicle):
    def __init__(self, brand, seats):
        super().__init__(brand, 4)       # reuse the parent's setup
        self.seats = seats

    def describe(self):                  # override
        return super().describe() + f" and {self.seats} seats"

class Rickshaw(Vehicle):
    def __init__(self):
        super().__init__("Rickshaw", 3)

print(Car("Toyota", 5).describe())
print(Rickshaw().describe())
print(issubclass(Car, Vehicle), isinstance(Rickshaw(), Car))

Output

Toyota with 4 wheels and 5 seats
Rickshaw with 3 wheels
True False
  • class Car(Vehicle): makes Car a child of Vehicle. It gets brand, wheels and describe() for free.
  • super().__init__(brand, 4) runs the parent’s setup, then the child adds its own seats attribute.
  • Overriding: Car defines its own describe(). Inside it, super().describe() reuses the parent version and extends it.
  • Rickshaw does not override describe(), so it uses the parent’s version unchanged.
  • issubclass(Car, Vehicle) is true, but a Rickshaw is not a Car.

Multiple Inheritance and the MRO

class Flyer:
    def move(self):
        return "flies"

class Swimmer:
    def move(self):
        return "swims"

    def dive(self):
        return "dives deep"

class Duck(Flyer, Swimmer):              # multiple inheritance
    pass

d = Duck()
print(d.move())                          # Flyer comes first
print(d.dive())
print([c.__name__ for c in Duck.__mro__])

Output

flies
dives deep
['Duck', 'Flyer', 'Swimmer', 'object']

A class can have more than one parent. When both parents define move(), Python searches classes in the method resolution order (MRO): the class itself, then its parents from left to right, then object. Duck(Flyer, Swimmer) finds Flyer.move first. dive() exists only in Swimmer, so that is where it comes from.

Types of Inheritance

TypeShape
SingleOne parent → one child (Vehicle → Car)
MultilevelA chain: Vehicle → Car → ElectricCar
HierarchicalOne parent, several children (Car and Rickshaw)
MultipleSeveral parents → one child (Duck)

Common Mistakes

  1. Forgetting super().__init__() in the child’s __init__, which leaves parent attributes unset and causes AttributeError later.
  2. Using inheritance for “has-a” relationships. A car has an engine; store an Engine object as an attribute instead of inheriting from it.
  3. Deep inheritance chains. More than two or three levels make code hard to follow.

Practice Exercises

Exercise 1. Create Animal with speak() returning “…”, and a Dog subclass that returns “Woof”.

Show answer
class Animal:
    def speak(self):
        return "..."

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

print(Dog().speak())   # Woof

Exercise 2. What does Duck.__mro__ print if the class is written Duck(Swimmer, Flyer), and what does move() return?

Show answer

Duck, Swimmer, Flyer, object. move() now returns “swims”, because Swimmer is searched first.

Frequently Asked Questions

What does super() do in Python?

It returns a proxy for the next class in the MRO, so you can call the parent’s version of a method, most often super().__init__(...).

Does Python support multiple inheritance?

Yes. A class can list several parents, and the MRO decides which method wins when names clash.

What is the object class?

Every class in Python ultimately inherits from object, which provides default methods such as __str__ and __eq__.

Summary

  • class Child(Parent): inherits the parent’s attributes and methods.
  • super() calls the parent’s version of a method.
  • Defining a method with the same name overrides the parent’s.
  • With multiple parents, the MRO searches left to right.

Next: Polymorphism and Encapsulation.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *