0
0
Pythonprogramming~5 mins

Polymorphism through inheritance in Python

Choose your learning style9 modes available
Introduction

Polymorphism lets different objects use the same action name but do different things. It helps write flexible and simple code.

When you have different types of animals and want each to make its own sound using the same method name.
When you want to handle different shapes and calculate their areas using one method name.
When you want to write code that works with many types of objects without changing the code.
When you want to add new types without changing existing code.
When you want to organize code so similar actions share the same name but behave differently.
Syntax
Python
class ParentClass:
    def method(self):
        # common method
        pass

class ChildClass(ParentClass):
    def method(self):
        # different behavior
        pass

Child classes override the method from the parent to change behavior.

Use the same method name in child classes for polymorphism.

Examples
Different animals have their own sound method but share the same name.
Python
class Animal:
    def sound(self):
        print("Some sound")

class Dog(Animal):
    def sound(self):
        print("Bark")

class Cat(Animal):
    def sound(self):
        print("Meow")
Function uses polymorphism to call the right sound method.
Python
def make_sound(animal):
    animal.sound()

make_sound(Dog())  # prints Bark
make_sound(Cat())  # prints Meow
Sample Program

This program shows how different animals use the same method name but make different sounds.

Python
class Animal:
    def sound(self):
        print("Some generic sound")

class Dog(Animal):
    def sound(self):
        print("Bark")

class Cat(Animal):
    def sound(self):
        print("Meow")

animals = [Dog(), Cat(), Animal()]

for animal in animals:
    animal.sound()
OutputSuccess
Important Notes

Polymorphism helps avoid many if-else checks for object types.

Always use the same method name in parent and child classes for polymorphism to work.

Summary

Polymorphism means one method name, many behaviors.

It works by overriding methods in child classes.

It makes code easier to extend and maintain.