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

Method Overriding in Python


Method overriding is a feature in Python that allows a subclass to provide a specific implementation of a method that is already defined in its parent class. It enables polymorphism, where the method in the subclass overrides the method in the parent class with the same name and parameters.

Basic Example of Method Overriding

In this example, the parent class Animal has a method speak(), which is overridden by the subclass Dog.

    class Animal:
        def speak(self):
            return "Animal makes a sound"

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

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

    print(animal.speak())  # Output: Animal makes a sound
    print(dog.speak())     # Output: Dog barks
        

Overriding and Extending Parent Class Methods

Sometimes, you might want to override a method but still use the functionality of the parent class's method. This can be done using the super() function.

    class Animal:
        def speak(self):
            return "Animal makes a sound"

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

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

Constructor Overriding

Constructors (__init__ methods) can also be overridden to provide specific initialization behavior for the subclass.

    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("Parrot", True)
    print(bird.name)      # Output: Parrot
    print(bird.can_fly)   # Output: True
        

Rules of Method Overriding

Advantages of Method Overriding

Conclusion

Method overriding is a core concept in object-oriented programming that enables a subclass to customize or extend the behavior of a method defined in its parent class. It ensures flexibility and allows developers to implement polymorphism effectively in their Python programs.



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