Skip to the content

Overriding methods

Python · Unit 13: Inheritance

If the child writes a method with the same name as one of the parent's, the child's replaces it. This is called overriding.

It only changes for the child's objects: the parent's objects keep their own.

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

class Cow(Animal):
    def sound(self):
        return "Moo"

print(Animal().sound())
print(Cow().sound())

Prints

...
Moo

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Multiple choice

    With p.move(), how does Python decide which move to run?

  3. 3. Find the bug

    A manager earns 300. It should print 300. Which line has the bug?

  4. 4. Complete the code

    A VIP ticket costs 30 more than a regular one. Complete it so it prints 80.

  5. 5. Predict the output

    What does this code print?

  6. 6. Find the bug

    With delivery, an order costs 50 more. It should print 250. Which line has the bug?

  7. 7. Predict the output

    __str__ can be overridden too. What does it print?

  8. 8. Find the case that fails

    A member gets a 10% discount, and a VIP customer gets the member's discount plus 50. pay(total) returns how much a VIP pays, and it should never be less than 0. Which call breaks it?

  9. 9. Predict the output

    speak belongs to the parent, but a cat calls it. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →