Method overriding is a feature of any object-oriented programming language that allows a subclass or child class to implement a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, parameters or signature, and return type (or sub-type) as a method in its super-class, the subclass method is said to override the method in the super-class.
To override a function, the following conditions must be met:
- There should be inheritance. Within a class, function overriding is not possible. We must create a child class from a parent class.
- The redefined function in the child class should have the same signature as the parent class, i.e. the same number of parameters.
Key Features of Python Method Overriding:
The following are some of the key features and benefits of Python method overriding:
- The concept of method overriding is derived from object-oriented programming.
- Method overriding allows us to change the implementation of a function defined in the parent class in the child class.
- The inheritance mechanism includes method overriding.
- Method overriding avoids code duplication while also improving the code by adding some extra properties.
Python Method Overriding Example:
# Parent class
class Shape:
# properties
data1 = "abc"
# function no_of_sides
def no_of_sides(self):
print("My sides need to be defined. I am from shape class.")
# function two_dimensional
def two_dimensional(self):
print("I am a 2D object. I am from shape class")
class Square (Shape):
data2 = "XYZ"
def no_of_sides (self):
print("I have 4 sides. I am from Square class")
def color(self):
print("I have teal color. I am from Square class.")
# Create an object of Square class
sq = Square()
# Override the no_of_sides of parent class
sq.no_of_sides()
# Will inherit this method from the parent class
sq.two_dimensional()
# It's own method color
sq.color()
Here,
- no_of_sides is the overridden method in the Shape class, since the Square class method – no_of_sides() will be overriding it (adding its own implementation).
- wo_dimensional is inherited by the sub_class(hence inherited method)
- color is a new method added in the Square class.
- data1 & data2 are individual properties of the classes.
- In the child class – Square, we have overridden the method no_of_sides() adding our implementation.
Output:
I have 4 sides. I am from Square class
I am a 2D object. I am from shape class
I have teal color. I am from Square class.
Note: also read about Access Modifiers in Python
Follow Me
Please follow me to read my latest post on programming and technology if you like my post.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Leave a Comment