0
0
Pythonprogramming~5 mins

Method overriding in Python

Choose your learning style9 modes available
Introduction

Method overriding lets a child class change how a method from its parent works. This helps customize behavior without changing the original code.

You want a child class to do something different when a method is called.
You have a general method in a parent class but need specific versions in child classes.
You want to reuse code but change only parts of it in subclasses.
You want to make your program easier to extend and maintain.
Syntax
Python
class Parent:
    def method(self):
        # original behavior
        pass

class Child(Parent):
    def method(self):
        # new behavior overriding parent method
        pass

The child class uses the same method name to replace the parent's method.

You can still call the parent method inside the child method using super() if needed.

Examples
The Dog class changes the sound method to print "Bark" instead of "Some sound".
Python
class Animal:
    def sound(self):
        print("Some sound")

class Dog(Animal):
    def sound(self):
        print("Bark")
The Car class overrides move to show a specific message.
Python
class Vehicle:
    def move(self):
        print("Moving")

class Car(Vehicle):
    def move(self):
        print("Car is driving")
The child calls the parent's method first, then adds its own message.
Python
class Parent:
    def greet(self):
        print("Hello from Parent")

class Child(Parent):
    def greet(self):
        super().greet()
        print("Hello from Child")
Sample Program

This program shows method overriding. The Penguin class changes the fly method to say penguins can't fly, even though the parent Bird class says "Flying in the sky".

Python
class Bird:
    def fly(self):
        print("Flying in the sky")

class Penguin(Bird):
    def fly(self):
        print("Penguins can't fly")

bird = Bird()
bird.fly()

penguin = Penguin()
penguin.fly()
OutputSuccess
Important Notes

Method overriding only works if the method names are exactly the same.

Use super() to call the parent method if you want to keep its behavior and add more.

Overriding helps make your code flexible and easier to change later.

Summary

Method overriding lets a child class change a parent's method behavior.

Use the same method name in the child class to override.

It helps customize and extend code without rewriting everything.