Method Overriding in Python

Method overriding is a feature of Object-oriented programming that enables you to change the behavior of inherited methods as per our specific needs. Here, the method in a derived class has the same name and the same number of arguments as the base class.

Base class's method is called overridden method and the derived class method is called overriding method.

Example: Python Method Overriding

#Python program to implement method overriding
class Animal:
   def sound(self):
      print('Animal makes sound.')

class Dog(Animal):
   def sound(self):
      print('Dog barks.')

d = Dog()
d.sound()

Output of the above program

Dog barks.

In the above code, you can see that Dog class is a subclass of Animal class. Dog class has overridden sound() method of Animal class. When we have called sound() method using Dog class object then "Dog barks" is printed instead of "Animal makes sound".

How to call base class overridden method from derived class?

There are two ways of calling base class overridden method-

  1. Using class name
  2. Using super()

Using class name to call base class method

Use class name followed by dot and then function name that you want to call. Syntax will be

ClassName.OverriddenMethod()
#Python Program to call base class overridden method using class name
class Animal:
   def sound(self):
      print('Animal makes sound.')

class Dog(Animal):
   def sound(self):
      Animal.sound(self)
      print('Dog barks.')

d = Dog()
d.sound()

Output of the above program

Animal makes sound.
Dog barks.

Using super() to call base class method

Use super() followed by dot and then function name that you want to call. Syntax will be

super().OverriddenMethod()
#Python Program to call base class overridden method using super()
class Animal:
   def sound(self):
      print('Animal makes sound.')

class Dog(Animal):
   def sound(self):
      super().sound()
      print('Dog barks.')

d = Dog()
d.sound()

Output of the above program

Animal makes sound.
Dog barks.