Method overriding in Python

Share Your Love

Method overriding in Python allows a subclass to provide a different implementation of a method that is already defined in its parent class. The subclass overrides the method to customize its behavior while maintaining the same method signature (name and parameters) as the parent class.

To override a method in Python, follow these steps:

  1. Define a class that inherits from the parent class.
  2. Declare a method in the subclass with the same name as the method in the parent class that you want to override.
  3. Provide the new implementation of the method in the subclass.

Here’s an example to illustrate method overriding:

class Animal:
    def speak(self):
        print("Animal speaks")


class Dog(Animal):
    def speak(self):
        print("Dog barks")


class Cat(Animal):
    def speak(self):
        print("Cat meows")


# Creating instances of Dog and Cat
dog = Dog()
cat = Cat()

# Calling the overridden methods
dog.speak()  # Output: Dog barks
cat.speak()  # Output: Cat meows

In the example above, the Animal class defines a speak the method that prints “Animal speaks”. The Dog class and Cat class inherit from Animal and override the speak the method with their own implementations.

When dog.speak() is called, it invokes the speak method of the Dog class, which prints “Dog barks” instead of the default “Animal speaks” from the parent class.

Similarly, when cat.speak() is called, it invokes the speak method of the Cat class, which prints “Cat meows” instead of the default “Animal speaks” from the parent class.

Method overriding allows you to customize the behavior of methods in subclasses, providing a way to adapt and extend the functionality of the parent class based on the specific requirements of each subclass.

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 411

Newsletter Updates

Enter your email address below to subscribe to our newsletter