Method overriding lets a child class change how a method works from its parent class. This helps customize behavior without changing the original code.
0
0
Method overriding behavior in Python
Introduction
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 pass
The child class uses the same method name to replace the parent's method.
You can still call the parent's method inside the child 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 start but also calls the parent's start using super().Python
class Vehicle: def start(self): print("Vehicle starting") class Car(Vehicle): def start(self): super().start() print("Car engine running")
Sample Program
This program shows how the Child class changes the greet method. Calling greet on Parent prints one message, and calling it on Child prints another.
Python
class Parent: def greet(self): print("Hello from Parent") class Child(Parent): def greet(self): print("Hello from Child") p = Parent() c = Child() p.greet() c.greet()
OutputSuccess
Important Notes
Method overriding only works if the method names are exactly the same.
Use super() to keep the original behavior and add new actions.
Overriding helps make your code flexible and easier to update later.
Summary
Method overriding lets child classes change parent class methods.
It uses the same method name in the child class.
Use super() to call the parent method if needed.