# Polymorphism

> Polymorphism means 'many forms' and refers to the ability of different objects to respond to the same method call in their own way. In Python,...

Canonical: https://www.internhack.in/learn/python/oop/polymorphism
Last updated: 2026-11-28

Difficulty: Intermediate

Polymorphism means 'many forms' and refers to the ability of different objects to respond to the same method call in their own way. In Python, polymorphism is deeply embedded in the language. When you call len() on a list, a string, or a dictionary, each type handles the call differently through its own \__len_\_ implementation. The caller does not need to know the specific type; it only needs to know that the object supports the operation.

Duck typing is Python's primary mechanism for polymorphism. The phrase comes from the saying: 'If it walks like a duck and quacks like a duck, it is a duck.' Python does not check an object's type before calling a method. It simply tries to call the method, and if the object has it, the call succeeds. This means unrelated classes can be used interchangeably as long as they implement the same interface (i.e., the same method names with compatible signatures).

Method overriding is the most explicit form of polymorphism. A subclass provides its own implementation of a method defined in its parent class. When the method is called on an instance of the subclass, the overriding version runs. This is commonly used with a base class that defines a generic interface and subclasses that provide specialized behavior.

Operator overloading lets you define how built-in operators (+, -, \*, ==, <, etc.) work with your custom objects. You implement this by defining special (dunder) methods like \__add_\_ for +, \__eq_\_ for ==, \__lt_\_ for <, and \__mul_\_ for \*. This makes your objects behave naturally with Python's syntax. For example, defining \__add_\_ lets you write obj1 + obj2 instead of obj1.add(obj2).

Polymorphic functions and iteration are everywhere in Python. Built-in functions like len(), str(), iter(), and sorted() all work through duck typing. For-loops call \__iter_\_ and \__next_\_. The print function calls \__str_\_. By implementing the right dunder methods, your custom objects integrate seamlessly with Python's built-in syntax and standard library functions.

## Code examples

### Duck typing with unrelated classes

```
class Dog:
    def speak(self):
        return 'Woof!'

class Cat:
    def speak(self):
        return 'Meow!'

class Robot:
    def speak(self):
        return 'Beep boop!'

def make_them_speak(things):
    for thing in things:
        print(thing.speak())

creatures = [Dog(), Cat(), Robot()]
make_them_speak(creatures)
```

Dog, Cat, and Robot have no common base class, yet make_them_speak works with all three because each implements speak(). This is duck typing: Python does not check the type, only that the method exists.

### Method overriding for polymorphic behavior

```
class Shape:
    def area(self):
        return 0

    def describe(self):
        return f'{self.__class__.__name__}: area = {self.area()}'

class Square(Shape):
    def __init__(self, side):
        self.side = side

    def area(self):
        return self.side  2

class Triangle(Shape):
    def __init__(self, base, height):
        self.base = base
        self.height = height

    def area(self):
        return 0.5 * self.base * self.height

shapes = [Square(4), Triangle(6, 3)]
for s in shapes:
    print(s.describe())
```

describe() is defined once in Shape and calls self.area(). Because each subclass overrides area(), the same describe() method produces different output depending on the actual type. This is runtime polymorphism.

### Operator overloading with \__add_\_ and \__eq_\_

```
class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

    def __repr__(self):
        return f'Vector({self.x}, {self.y})'

v1 = Vector(1, 2)
v2 = Vector(3, 4)
v3 = v1 + v2

print(v3)
print(v1 + v2 == Vector(4, 6))
print(v1 == v2)
```

\__add_\_ is called when you use + between two Vector objects. \__eq_\_ handles ==. \__repr_\_ provides the string representation used by print. These dunder methods make Vector work naturally with Python operators.

### Polymorphism with built-in functions

```
class Playlist:
    def __init__(self, name, songs):
        self.name = name
        self.songs = songs

    def __len__(self):
        return len(self.songs)

    def __str__(self):
        return f'{self.name} ({len(self)} songs)'

    def __contains__(self, song):
        return song in self.songs

p = Playlist('Road Trip', ['Song A', 'Song B', 'Song C'])
print(len(p))
print(str(p))
print('Song B' in p)
print('Song D' in p)
```

By implementing \__len_\_, \__str_\_, and \__contains_\_, the Playlist class works seamlessly with len(), str()/print(), and the 'in' operator. This is polymorphism through Python's protocol system.

## Key points

- Duck typing means you should program to an interface, not a type. If an object has the methods you need, it works.
- Python does not have method overloading (multiple methods with the same name but different parameter lists) like Java. Use default arguments or \*args/kwargs instead.
- Operator overloading methods should return new objects rather than modifying self, matching the behavior of built-in types.
- The \__repr_\_ method should ideally return a string that could recreate the object, while \__str_\_ should return a human-readable description.

## Interview tips

- Explain duck typing with a concrete example: 'If I need an object that has a read() method, I don't care if it is a file, a socket, or a StringIO buffer.'
- Know the common operator overloading methods: \__add_\_, \__sub_\_, \__mul_\_, \__eq_\_, \__lt_\_, \__len_\_, \__str_\_, \__repr_\_, \__contains_\_, \__getitem_\_.
- Describe how polymorphism in Python differs from statically typed languages: there are no interfaces or abstract method requirements enforced at compile time, just runtime duck typing.

## Concepts covered

duck typing, method overriding, operator overloading, \__add_\_, \__len_\_, polymorphic functions

Previous: [Encapsulation & Abstraction](https://www.internhack.in/learn/python/oop/encapsulation-abstraction) · Next: [Magic Methods (Dunder Methods)](https://www.internhack.in/learn/python/oop/magic-methods) · [All of Object-Oriented Programming](https://www.internhack.in/learn/python/oop)

## More Object-Oriented Programming lessons

- [Classes & Objects](https://www.internhack.in/learn/python/oop/classes-and-objects)
- [Inheritance](https://www.internhack.in/learn/python/oop/inheritance)

## Related

- [Learn](https://www.internhack.in/learn)
- [Python](https://www.internhack.in/learn/python)
- [Object-Oriented Programming](https://www.internhack.in/learn/python/oop)
