Chapter 48 of 54

Polymorphism & Dunder Methods in Python

Have you noticed that len() works on strings, lists and dictionaries, and that + adds numbers but joins strings? One name, different behaviour depending on the object. This idea is called polymorphism, and it is one of the four pillars of OOP.

In this chapter, you'll see how polymorphism works in Python, and how special dunder methods (like __str__ and __add__) let your own classes work with built-in functions and operators, just like Python's built-in types.

What is Polymorphism?

Polymorphism (Greek for "many forms") means the same operation or method name can behave differently depending on the type of object it is used with.

You have been using it since the beginning:

print(len("hello"), len([1, 2, 3]), len({"a": 1}))
print(5 + 3, "5" + "3", [1] + [2])

Output:

5 3 1
8 53 [1, 2]

len() counts characters, items or keys. + adds, concatenates or joins lists. The code you write stays the same; each type decides what it means.


Polymorphism Through Method Overriding

In the Inheritance chapter, you saw child classes override a parent's method. Combined with a loop, this lets one piece of code work with many types:

class Shape:
    def area(self):
        return 0

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

    def area(self):
        return self.side ** 2

class Circle(Shape):
    def __init__(self, r):
        self.r = r

    def area(self):
        return round(3.14159 * self.r ** 2, 2)

for s in [Square(4), Circle(2)]:
    print(type(s).__name__, s.area())

Output:

Square 16
Circle 12.57

The loop just calls s.area(). Python decides at runtime which area() to run, based on the actual object. If you add a Triangle class tomorrow, the loop does not change at all.


Duck Typing

Python goes one step further. Objects don't even need a common parent. If an object has the method you call, it works:

"If it walks like a duck and quacks like a duck, it's a duck." Python cares about what an object can do, not what class it is.

class Duck:
    def speak(self):
        return "Quack"

class Robot:
    def speak(self):
        return "Beep boop"

def make_it_speak(thing):
    print(thing.speak())

make_it_speak(Duck())
make_it_speak(Robot())

Output:

Quack
Beep boop

Duck and Robot are unrelated, but both have speak(), so make_it_speak() accepts both. If you passed an object without speak(), you'd get an AttributeError.


What Are Dunder Methods?

Dunder ("double underscore") methods, also called magic or special methods, have names like __init__ and __str__. Python calls them automatically when you use built-in functions or operators on an object.

You already know one: __init__ runs when you create an object. Behind the scenes, every operator is a method call:

You write        Python actually calls
---------        ---------------------
a + b       ->   a.__add__(b)
len(a)      ->   a.__len__()
str(a)      ->   a.__str__()
a == b      ->   a.__eq__(b)
a[0]        ->   a.__getitem__(0)
x in a      ->   a.__contains__(x)

You can check this yourself: (5).__add__(3) returns 8. By defining these methods in your class, you decide how your objects behave with Python's built-in syntax. That is operator overloading.


Readable Objects: __str__ and __repr__

By default, printing an object is not helpful:

class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

b = Book("Wings of Fire", "A. P. J. Abdul Kalam")
print(b)

Output (the address varies):

<__main__.Book object at 0x000002548E0C86E0>

Let's add both methods:

class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

    def __str__(self):
        return f"{self.title} by {self.author}"

    def __repr__(self):
        return f"Book({self.title!r}, {self.author!r})"

b = Book("Wings of Fire", "A. P. J. Abdul Kalam")
print(b)
print(repr(b))
print([b])

Output:

Wings of Fire by A. P. J. Abdul Kalam
Book('Wings of Fire', 'A. P. J. Abdul Kalam')
[Book('Wings of Fire', 'A. P. J. Abdul Kalam')]
__str____repr__
AudienceEnd usersDevelopers (debugging)
Used byprint(), str(), f-stringsrepr(), the interactive shell, items inside lists
GoalFriendly and readableUnambiguous, ideally looks like code to recreate the object
If missingFalls back to __repr__Default <... object at 0x...>

Notice that printing a list of books uses __repr__, not __str__. If you write only one, write __repr__, because str() falls back to it. (The !r in the f-string inserts the repr() of the value, which adds the quotes around strings.)


Operator Overloading: __add__, __mul__, __eq__

A 2D vector is a classic example:

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 __mul__(self, k):
        return Vector(self.x * k, self.y * k)

    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(2, 3)
v2 = Vector(1, 5)

print(v1 + v2)
print(v1 * 3)
print(v1 == Vector(2, 3))
print(v1 != v2)

Output:

Vector(3, 8)
Vector(6, 9)
True
True

Some important details:

  • Operator methods should return a new object, not modify self. v1 + v2 should not change v1.

  • Without __eq__, == compares identity (same object in memory), so two objects with equal values would be "not equal".

  • Python automatically uses __eq__ to answer != when __ne__ is not defined.

  • 3 * v1 fails with TypeError: unsupported operand type(s) for *: 'int' and 'Vector'. The left operand's method runs first, and int doesn't know about vectors. To support it, define __rmul__ (the "reflected" version).

  • Defining __eq__ makes objects unhashable unless you also define __hash__, so they can't be put in a set or used as dictionary keys. Python raises a TypeError mentioning "unhashable type".

Returning NotImplemented

If your method receives a type it can't handle, return the special value NotImplemented. Python then tries the other operand's reflected method and, if that fails too, raises a clean TypeError:

class Money:
    def __init__(self, amount):
        self.amount = amount

    def __add__(self, other):
        if not isinstance(other, Money):
            return NotImplemented
        return Money(self.amount + other.amount)

    def __radd__(self, other):
        if other == 0:          # lets sum() work, since sum starts from 0
            return self
        return self.__add__(other)

    def __repr__(self):
        return f"Money({self.amount})"

print(Money(100) + Money(50))
print(sum([Money(10), Money(20), Money(30)]))
Money(100) + 5

Output (the last line is the error raised by Money(100) + 5):

Money(150)
Money(60)
TypeError: unsupported operand type(s) for +: 'Money' and 'int'

Container Behaviour: __len__, __getitem__, __contains__

You can make your objects behave like lists:

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

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

    def __getitem__(self, index):
        return self.songs[index]

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

p = Playlist("Coding", ["Lofi Beats", "Rain Sounds", "Piano Focus"])

print(len(p))
print(p[0])
print(p[-1])
print(p[0:2])
print("Rain Sounds" in p)

for song in p:
    print("Playing:", song)

Output:

3
Lofi Beats
Piano Focus
['Lofi Beats', 'Rain Sounds']
True
Playing: Lofi Beats
Playing: Rain Sounds
Playing: Piano Focus

Because __getitem__ simply passes the index to the list, negative indexes and slices work for free. Even the for loop works: when a class has no __iter__, Python falls back to calling __getitem__ with 0, 1, 2, ... until an IndexError. (You'll learn the proper __iter__ way in the Iterators & Generators chapter.) Also, __len__ affects truthiness: an empty playlist counts as False in an if.


Comparisons and Sorting: __lt__

Defining __lt__ (less than) is enough for sorted(), min() and max() to work on your objects:

class Student:
    def __init__(self, name, cgpa):
        self.name = name
        self.cgpa = cgpa

    def __lt__(self, other):
        return self.cgpa < other.cgpa

    def __repr__(self):
        return f"{self.name}({self.cgpa})"

students = [Student("Asha", 9.1), Student("Ravi", 8.4), Student("Meera", 8.9)]
print(sorted(students))
print(max(students))

Output:

[Ravi(8.4), Meera(8.9), Asha(9.1)]
Asha(9.1)

Even a > b works here: Python reflects it to b.__lt__(a).


Common Dunder Methods

MethodTriggered by
__init__(self, ...)Creating an object
__str__(self)print(obj), str(obj)
__repr__(self)repr(obj), shell, inside containers
__len__(self)len(obj)
__getitem__(self, key)obj[key]
__setitem__(self, key, value)obj[key] = value
__contains__(self, item)item in obj
__add__, __sub__, __mul__, __truediv__+, -, *, /
__eq__, __lt__, __le__, __gt__, __ge__==, <, <=, >, >=
__bool__(self)bool(obj), if obj:
__call__(self, ...)obj(...) (calling an object like a function)
__hash__(self)hash(obj), sets, dict keys

Abstract Base Classes

Sometimes a parent class exists only to define what methods children must have, not how. The built-in abc module enforces this:

from abc import ABC, abstractmethod

class Payment(ABC):
    @abstractmethod
    def pay(self, amount):
        pass

class UPI(Payment):
    def pay(self, amount):
        print(f"Paid Rs.{amount} via UPI")

class Card(Payment):
    def pay(self, amount):
        print(f"Paid Rs.{amount} via Card")

for method in [UPI(), Card()]:
    method.pay(500)

Payment()

Output (the last line is the error raised by Payment()):

Paid Rs.500 via UPI
Paid Rs.500 via Card
TypeError: Can't instantiate abstract class Payment without an implementation for abstract method 'pay'

You cannot create a Payment object directly, and any subclass that forgets to implement pay() also cannot be created. This is how Python achieves abstraction: hiding the details behind a common interface.


Does Python Support Method Overloading?

Not in the Java sense. If you define two methods with the same name, the second simply replaces the first:

class Calc:
    def add(self, a, b):
        return a + b

    def add(self, a, b, c):      # replaces the first add
        return a + b + c

Calc().add(1, 2)

This raises TypeError: Calc.add() missing 1 required positional argument: 'c'. Use default arguments instead: def add(self, a, b, c=0).

OverridingOverloading
MeaningChild redefines a parent's methodSame name, different parameters
Python supportYesNo (use default or variable arguments)
DecidedAt runtimeAt compile time (in Java/C++)

Common Mistakes

  • Returning a string from __str__ is mandatory. Using print() inside __str__ instead of return causes TypeError: __str__ returned non-string (type NoneType) (the print() runs, but the method returns None).

  • Modifying self in __add__ instead of returning a new object.

  • Defining __eq__ and then using the objects in a set without defining __hash__.

  • Calling dunder methods directly, like obj.__len__(). Use len(obj); the dunder exists for Python to call.

  • Inventing your own dunder names like __mymethod__. Those names are reserved for Python.


Summary

  • Polymorphism means one interface, many behaviours: the same call works on different types.

  • Python achieves it through method overriding, duck typing and operator overloading.

  • Dunder methods are called automatically by built-in functions and operators.

  • __str__ is for users, __repr__ for developers; write at least __repr__.

  • Return NotImplemented for unsupported types, and use abc to define abstract interfaces.

Dunder methods let your classes speak Python's language: once you define them, your objects work with print, len, +, ==, in and sorted just like built-in types.

Interview tips: Expect "What is the difference between __str__ and __repr__?", "What is duck typing?" and "Does Python support method overloading?". Being able to write a small __add__ or __eq__ on the spot is a big plus.

Practice: Build a Fraction class with __add__, __eq__ and __str__ (for example, 1/2 + 1/3 prints 5/6). Then build a Matrix class that supports + and len().