Signup/Sign In

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:

  1. Inheritance should be there. Function overriding cannot be done within a class. We need to derive a child class from a parent class.
  2. 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 public and protected(access modifiers in python) variables and methods, for example,

# 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()

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 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.")

Let's create a child class Herbivorous which will extend the class Animal:

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

In the child class Herbivorous we have overridden the method feed().

So now when 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()

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.