Velamuvi AIAcademy

Lesson 10 of 15 · Relationships

Overriding and super()

Learn how a Python child class replaces or extends a parent's method, how super() calls the parent version, how to add attributes in a child __init__, and what the MRO is.

  • 7 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • What overriding a method means
  • What super() does and when to use it
  • How to give a child class extra attributes in __init__
  • How to extend a parent's method instead of replacing it
  • What the method resolution order is

Children can do things differently

In the last lesson, children only added new methods. Often a child needs to do an inherited job in its own way. All animals make a sound, but not the same sound.

Try it yourselfPython
class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return f"{self.name} makes a sound"


class Dog(Animal):
    def speak(self):
        return f"{self.name} says Woof!"


class Cow(Animal):
    def speak(self):
        return f"{self.name} says Moo!"


class Fish(Animal):
    pass


for pet in [Dog("Rex"), Cow("Gauri"), Fish("Nemo")]:
    print(pet.speak())

Dog and Cow override speak. Fish does not, so it uses the parent's version. Remember the lookup order: Python checks the child class first, so the child's method wins.

Calling the parent: super()

Sometimes you do not want to throw the parent's method away. You want to run it and do a bit more.

The most important place to use it is __init__.

Adding attributes in a child's __init__

Say a Dog needs a breed as well as a name. If the child writes its own __init__, it overrides the parent's, so the parent's setup no longer runs. Use super().__init__(...) to run it first, then add the extra attributes.

Try it yourselfPython
class Animal:
    def __init__(self, name, age):
        self.name = name
        self.age = age


class Dog(Animal):
    def __init__(self, name, age, breed):
        super().__init__(name, age)     # let the parent set name and age
        self.breed = breed              # then add what is new


rex = Dog("Rex", 3, "Labrador")
print(rex.name, rex.age, rex.breed)

The child does not repeat self.name = name and self.age = age. The parent already knows how to do that. If the parent's setup ever changes, every child benefits automatically.

Extending a method

Try it yourselfPython
class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

    def withdraw(self, amount):
        if amount > self.balance:
            return "Not enough money"
        self.balance -= amount
        return f"Withdrew {amount}. Balance: {self.balance}"


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

    def withdraw(self, amount):
        if amount > self.limit:
            return f"Savings accounts allow at most {self.limit} per withdrawal"
        return super().withdraw(amount)     # the normal rules still apply


savings = SavingsAccount("Ada", 800)
print(savings.withdraw(500))      # passes both rules
print(savings.withdraw(400))      # passes the limit, but the parent's rule refuses it
print(savings.withdraw(5000))     # refused by the child's new rule

SavingsAccount.withdraw adds one extra rule, then hands over to the parent for everything else. It does not copy the balance-checking code.

This works for any method, including magic methods:

Try it yourselfPython
class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price

    def __str__(self):
        return f"{self.name}: Rs {self.price}"


class DiscountedProduct(Product):
    def __init__(self, name, price, discount):
        super().__init__(name, price)
        self.discount = discount

    def __str__(self):
        return super().__str__() + f" ({self.discount}% off)"


print(Product("Mug", 250))
print(DiscountedProduct("Lamp", 900, 20))

Method resolution order

Every class can show you its MRO:

Try it yourselfPython
class Animal:
    pass


class Dog(Animal):
    pass


class Puppy(Dog):
    pass


for cls in Puppy.__mro__:
    print(cls.__name__)

When you call a method on a Puppy, Python looks in Puppy, then Dog, then Animal, then object, and uses the first one it finds. super() follows this same order: it means "the next class after me in the MRO".

Common mistakes

Practice exercise

Build a child class that adds an attribute with super().__init__ and extends a parent method.

Your solutionPython
class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def describe(self):
        return f"{self.name} earns {self.salary}"


# Write a child class Manager(Employee):
# - __init__(self, name, salary, team_size) uses super() for name and salary,
#   then stores team_size
# - describe(self) extends the parent's describe with " and leads 4 people"
#   (use the real team_size)


print(Employee("Alan", 50000).describe())
print(Manager("Ada", 90000, 4).describe())

# Output must be exactly:
# Alan earns 50000
# Ada earns 90000 and leads 4 people
Knowledge check

Inside a child class's __init__, what does super().__init__(name) do?

Summary

  • Overriding means a child defines a method with the same name as its parent's. The child's version wins.
  • super().method() runs the parent's version of a method.
  • In a child's __init__, call super().__init__(...) first, then add the new attributes.
  • Extending a method means overriding it and calling super() inside, adding to the parent's behaviour.
  • The MRO is the order Python searches classes. View it with ClassName.__mro__.

Next: how one piece of code can work with many different kinds of objects.

Finished reading? Tick it off to track your progress.