Topics

Method Overriding in python

Welcome to another tutorial, here you will learn about Method overriding in Python.

In OOP, method overriding is a concept that allows changes to be made in the implementation of a function in the child class that defined the parent class. The method overriding is the ability of a child class to change the implementation of any method which is already provided by one of its parent classes (or ancestors).

 

Conditions required for overriding a function:

  • Inheritance should be there: All Function overriding cannot be done within a class. As such we need to derive a child class from a parent class.
  • And, the function that is redefined in the child class should have the same signature as the parent class, that is, the same number of parameters.

From the tutorial on the concept of inheritance, you learned that when a child class inherits a parent class it automatically gains access to its public and protected variables and methods. Check the example below:

# parent class
class Parent:
    # some random function
    def anything(self):
        print('Function defined in parent class!')
        
# child class
class Child(Parent):
    # empty class definition
    pass


obj2 = Child()
obj2.anything()

Output:

Function defined in parent class!

The child class can access the parent class methods, as well as provide new implementation to the parent class methods, and this is known as Method Overriding.

 

Python Method Overriding Example

Now, check the example below. It is the same as the one used in the tutorial on Inheritance. We have a parent class named Animal:

class Animal:
    # properties
	multicellular = True
	# Eukaryotic means Cells with Nucleus
	eukaryotic = True
	
	# function breathe
	def breathe(self):
	    print("I breathe oxygen.")
    
    # function feed
	def feed(self):
	    print("I eat food.")

So, we will create a child class named Herbivorous. This class will extend the class Animal:

class Herbivorous(Animal):
    
    # function feed
	def feed(self):
	    print("I eat only plants. I am vegetarian.")

From the code above, in the child class Herbivorous, the method feed() has been overridden.

Thus, if we create an object of the class Herbivorous and call the method feed() the overridden version will be executed.

herbi = Herbivorous()
herbi.feed()
# calling some other function
herbi.breathe()

Output:

I eat only plants. I am vegetarian.
I breathe oxygen.