Overriding methods in Python

Coding with Python

🕑 This lesson will take about 10 minutes

Overriding methods

Overriding is a feature of object-oriented programming (OOP) that allows a sub-class to provide a specific implementation of a method that is already definedin the parent class (or super class). When you create a method in a sub-class that has the same name as a method in its parent class, then the method in the sub-class is said to “override” the method in the parent class.

For example, let’s say you create a class for different types of enemies in a game. You might start with a parent class (or super class) that has some attributes and methods. Let’s say you have a method called Attack that has some basic functionality. You might then create sub-classes of the Enemy class such as Knight, Troll, Wizard, etc. Each of these enemies might have a different type of attack, so you can create an Attack method (the same name as the method in the Enemy parent class) that overrides the functionality of the Attack method in the parent class. For example, a troll might punch, a knight might wield a sword, a wizard might cast a spell, etc. Each of these enemies can have a method called Attack, but the method performs different functionality depending on whether it is called on an enemy from the Enemy class, Troll sub-class, Knight sub-class, Wizard sub-class, etc.

Check out the example code below.

Overloading methods

Overloading is another concept in object-oriented programming. Method overloading is a method used in object-oriented programming where multiple methods can have the same name but perform different functionality depending on the number or types of parameters that are provided to the method when it is called on object. Overloading is not directly supported in Python (like it is in other languages such as Java, C++ or C#), however, you can still achieve similar behaviour by using default argument values or variable-length argument lists for a method. Here is a simple example using default argument values:

Next lesson: Data hiding