Geek Slack

Start creating your course and become a part of GeekSlack.

Introduction to Python
About Lesson



Python Polymorphism


Python Polymorphism

Polymorphism is the ability of different objects to respond to the same message or method call in different ways.

1. Method Overriding

Inheritance in Python allows methods to be overridden in a subclass, providing a form of polymorphism.

Example:

class Animal:
    def sound(self):
        return "Some sound"

class Dog(Animal):
    def sound(self):
        return "Woof!"

class Cat(Animal):
    def sound(self):
        return "Meow!"

dog = Dog()
cat = Cat()

print(dog.sound())  # Output: Woof!
print(cat.sound())  # Output: Meow!

2. Duck Typing

Python’s dynamic typing allows objects of different types to be used interchangeably if they support the same set of methods.

Example:

class Dog:
    def sound(self):
        return "Woof!"

class Cat:
    def sound(self):
        return "Meow!"

def make_sound(animal):
    return animal.sound()

dog = Dog()
cat = Cat()

print(make_sound(dog))  # Output: Woof!
print(make_sound(cat))  # Output: Meow!

Conclusion

Polymorphism is a powerful concept in object-oriented programming that allows for flexible and reusable code. Python’s dynamic nature and support for inheritance enable polymorphic behavior to be easily implemented and leveraged in applications.

Join the conversation