polymorphism

Polymorphism is a concept in object-oriented programming (OOP) that allows objects of different classes to be treated the same. It shifts the focus from data types to behaviors.

Polymorphism enables you to use a single interface to represent different underlying classes. In Python, polymorphism is achieved primarily through duck typing, but you can also implement it through inheritance and method overriding.

Polymorphism enhances flexibility and maintainability by allowing you to write more generic and reusable code.

Examples

Here’s an example of polymorphism through duck typing:

Python birds.py
class Duck:
    def swim(self):
        print("The duck is swimming.")

class Albatros:
    def swim(self):
        print("The albatros is swimming.")

The two classes don’t share a common base class. Because they share the same interface, you can still use them in the same way:

Python
>>> from birds import Duck, Albatros

>>> birds = [Duck(), Albatros()]

>>> for bird in birds:
...     bird.swim()
...
The duck is swimming.
The albatros is swimming.

Here’s an example of polymorphism using inheritance and method overriding in Python:

Python animals.py
class Animal:
    def speak(self):
        print("Animal speaks")

class Dog(Animal):
    def speak(self):
        print("Woof, Woof")

class Cat(Animal):
    def speak(self):
        print("Meow, Meow")

def make_animal_speak(animal):
    animal.speak()

In this example, both Dog and Cat are subclasses of Animal and override the .speak() method. You can use instances of these classes the same way:

Python
>>> from animals import Dog, Cat

>>> dog = Dog()
>>> cat = Cat()

>>> make_animal_speak(dog)
Woof, Woof
>>> make_animal_speak(cat)
Meow, Meow

The make_animal_speak() function demonstrates polymorphism by accepting any animal that inherits from Animal and calling its .speak() method, regardless of the specific type of animal.

Tutorial

Python Classes: The Power of Object-Oriented Programming

In this tutorial, you'll learn how to create and use full-featured classes in your Python code. Classes provide a great way to solve complex programming problems by approaching them through models that represent real-world objects.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated March 6, 2025 • Reviewed by Martin Breuss