Method Overriding in Python
Method overriding is a concept of object oriented programming that allows us to change the implementation of a function in the child class that is defined in the parent class. It is the ability of a child class to change the implementation of any method which is already provided by one of its parent class(ancestors).
Following conditions must be met for overriding a function:
- Inheritance should be there. Function overriding cannot be done within a class. We need to derive a child class from a parent class.
- The function that is redefined in the child class should have the same signature as in the parent class i.e. same number of parameters.
As we have already learned about the concept of Inheritance, we know that when a child class inherits a parent class it also get access to it
protected(access modifiers in python) variables and methods, for example,
# parent class
# some random function
print('Function defined in parent class!')
# child class
# empty class definition
obj2 = Child()
Function defined in parent class!
While the child class can access the parent class methods, it can also provide a new implementation to the parent class methods, which is called method overriding.
Python Method Overriding Example
Let's take a very cool example which we also had in the inheritance tutorial. There is a parent class named
multicellular = True
# Eukaryotic means Cells with Nucleus
eukaryotic = True
# function breathe
print("I breathe oxygen.")
# function feed
print("I eat food.")
Let's create a child class
Herbivorous which will extend the class
# function feed
print("I eat only plants. I am vegetarian.")
In the child class
Herbivorous we have overridden the method
So now when we create an object of the class
Herbivorous and call the method
feed() the overridden version will be executed.
herbi = Herbivorous()
# calling some other function
I eat only plants. I am vegetarian.
I breathe oxygen.
Click on Run to see the code in action and feel free to make changesto it and run again.