Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Overriding Methods in Python


Method overriding in Python allows a subclass to provide a specific implementation of a method that is already defined in its parent class. It is a key feature of object-oriented programming and enables polymorphism, which allows you to use the same method name in different classes with unique behaviors.

Example 1: Basic Method Overriding

In this example, we create a parent class Animal with a method speak(). The subclass Dog overrides the speak() method to provide a specific implementation.

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

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

    # Example usage
    animal = Animal()
    dog = Dog()

    print(animal.speak())  # Output: Animal speaks
    print(dog.speak())     # Output: Dog barks
        

Example 2: Overriding with Additional Behavior

In this example, the subclass calls the parent class method using super() and adds additional behavior to it.

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

    class Cat(Animal):
        def speak(self):
            original_speak = super().speak()
            return f"{original_speak} and Cat meows"

    # Example usage
    cat = Cat()
    print(cat.speak())  # Output: Animal speaks and Cat meows
        

Example 3: Constructor Overriding

Constructors (__init__ methods) can also be overridden in subclasses. Here's an example:

    class Animal:
        def __init__(self, name):
            self.name = name

    class Bird(Animal):
        def __init__(self, name, can_fly):
            super().__init__(name)
            self.can_fly = can_fly

    # Example usage
    bird = Bird("Sparrow", True)
    print(bird.name)      # Output: Sparrow
    print(bird.can_fly)   # Output: True
        

Key Points

Conclusion

Method overriding is a powerful feature in Python that promotes code reuse and enables polymorphism. It is widely used in object-oriented programming to implement specific behaviors in subclasses while maintaining a common interface in the parent class.



Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java