CodeMIRAI
0 XP

Special (dunder) methods

2 min read 5 runnable examples Quiz included

Methods with double underscores on both sides, like __init__, are special methods (nicknamed "dunder" methods, for double underscore). Python calls them for you when you use built-in syntax, so your objects can behave like built-in types.

__str__ and __repr__: how an object prints

Without them, printing an object isn't helpful:

Python
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

print(Point(3, 4))

Define __str__ for a readable display and __repr__ for an unambiguous, developer-facing one:

Python
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __str__(self):
        return f"({self.x}, {self.y})"

    def __repr__(self):
        return f"Point({self.x}, {self.y})"

p = Point(3, 4)
print(p)              # uses __str__
print(repr(p))        # uses __repr__
print([p, p])         # lists show their items with __repr__

__eq__: what == means

By default, == between two objects checks whether they're the same object. Define __eq__ to compare their values:

Python
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

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

print(Point(1, 2) == Point(1, 2))
print(Point(1, 2) == Point(2, 1))

Arithmetic: __add__ and friends

Python
class Money:
    def __init__(self, amount, currency="INR"):
        self.amount, self.currency = amount, currency

    def __add__(self, other):
        if self.currency != other.currency:
            raise ValueError("Currencies differ")
        return Money(self.amount + other.amount, self.currency)

    def __mul__(self, factor):
        return Money(self.amount * factor, self.currency)

    def __str__(self):
        return f"{self.currency} {self.amount:,.2f}"

price = Money(250)
print(price + Money(99.5))
print(price * 3)

Length, comparison and sorting

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

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

    def __lt__(self, other):            # makes < work, which sorted() uses
        return len(self) < len(other)

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

lists = [Playlist("Chill", ["a", "b", "c"]), Playlist("Focus", ["d"]), Playlist("Party", ["e", "f"])]
print(len(lists[0]))
print(sorted(lists))

Common special methods

MethodCalled by
__init__Thing(...)
__str__ / __repr__print(x), str(x) / repr(x)
__len__len(x)
__eq__, __lt__, __le__...==, <, <= ...
__add__, __sub__, __mul__+, -, *
__contains__item in x
__getitem__x[key]
__iter__for item in x
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.