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:

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:

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:

Previous Post
Next Post

Leave a Reply