Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

community creator

How to do method overriding in Python

Akshara S

Method overriding in Python is when you have two methods with the same name that each perform different tasks. This is an important feature of inheritance in Python.

In method overriding, the child class can change its functions that are defined by its ancestral classes. In other words, the child class has access to the properties and functions of the parent class method while also extending additional functions of its own to the method. If a method in a superclass coincides with that of a subclass, then the subclass is said to override the superclass.

There are two prerequisite conditions for Method overriding:

  1. Inheritance should be present in the code, method overriding cannot be performed in the same class, and overriding can only be executed when a child class is derived through inheritance.

  2. The child class should have the same name and the same number of parameters as the parent class.

Invoking a parent class or child class method depends upon the object being used to invoke. The reference object determines the execution of an overridden method.


class Animal:
    def Walk(self):
        print('Hello, I am the parent class')

class Dog(Animal):
    def Walk(self):
        print('Hello, I am the child class')
print('The method Walk here is overridden in the code')

#Invoking Child class through object r

r = Dog()

#Invoking Parent class through object r

r = Animal()


community creator

View all Courses

Keep Exploring