Class methods can be overridden.

A child class can use a method with the same name as one it inherits. Python then calls the child's version. That is overriding, and it is how you change behaviour without touching the parent class.

Let’s create a parent class and a class. The class will inherit from the parent class, meaning it will have all of its methods.

overriding methods of a class

Create a parent class Robot. Then a class that inherits from the class Robot. We add a method action that we override:

class Robot:
def action(self):
print('Robot action')

class HelloRobot(Robot):
def action(self):
print('Hello world')

r = HelloRobot()
r.action()

Instance r is created using the class HelloRobot, that inherits from parent class Robot.

The HelloRobot class inherits the method action from its parent class, but its overridden in the class itself.

Execute the program to see:
abstract-base-classes.md

Hello world

Overriding methods

The method is overwritten. This is only at class level, the parent class remains intact.
If we add another class that inherits, let’s see what happens.

Try the program below and find out why it outputs differently for the method action:

class Robot:
def action(self):
print('Robot action')

class HelloRobot(Robot):
def action(self):
print('Hello world')

class DummyRobot(Robot):
def start(self):
print('Started.')

r = HelloRobot()
d = DummyRobot()

r.action()
d.action()

What you need to know

  • The method name has to match exactly, including the spelling.
  • The signature should match too, so the caller does not notice a difference.
  • super().method() calls the version from the parent class. Useful to add to it instead of replacing it.
  • The parent class is untouched, so other objects of that class keep working.
  • Two classes with the same parent and no override between them behave the same.

Overriding gets more useful with bigger classes. A base class handles the common part and each child changes only the part that is different.

The fastest way to learn this is to write it yourself. The PyChallenge exercises run in your browser, no install needed.