Python

Overriding Methods

Class methods can be overridden.

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.

Related course: Python Beyond the Basics – Object-Oriented Programming

Example

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.

method override

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()

Previous Post Next Post

Cookie policy | Privacy policy | ©

OOP