Codiqo

Learn Python · lesson 58 of 60 · about 9 minutes

Overriding and super()

Give a child class its own version of a method, and still use the parent's.

What you'll learn

  • Override a method in a child class
  • Call the parent's version with super()
  • Extend __init__ with extra attributes

Sam's cactus

Sam has a new plant, a cactus called Spike. It's a Plant like the basil, but it only dries out every third day, and the assistant should say it's a cactus: Spike: water 1/5 (cactus). So Cactus(Plant) overrides day_passes and __str__, and each one uses the parent's version with super() instead of copying it.

Your own version

If a child class defines a method with the same name as one in the parent, the child's version wins. This is called overriding. Python always looks in the object's own class first, then in its parent.

Each animal speaks differently

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

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

class Fish(Animal):
    pass

for pet in [Dog(), Fish()]:
    print(pet.speak())

Output

Woof
...

Using the parent's version too

super() gives you the parent class, so super().speak() runs the parent's speak.

It's most useful in __init__: super().__init__(name) lets the parent set up the shared attributes, then the child adds its own.

Extending __init__

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

class Dog(Animal):
    def __init__(self, name, trick):
        super().__init__(name)
        self.trick = trick

d = Dog("Rex", "roll over")
print(d.name, "can", d.trick)

Output

Rex can roll over

Three uses of super()

Cactus.__init__ calls super().__init__(name) first, so the cactus gets its name and its 3 water like any plant, and then adds self.days = 0 to count the days. day_passes adds one to the days and only calls super().day_passes() on every third one, so the water goes down a third as often. And __str__ takes the plant's own text from super().__str__() and adds (cactus), so a dry cactus still says Spike: dry, water it now! (cactus). give_water isn't overridden at all, so watering works just as it does for the basil.

Tip

If a child's __init__ forgets super().__init__(...), the parent's attributes never get set, and using them raises an AttributeError.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.