Python · Module 5 · Lesson 41 min read

Special (Dunder) Methods

What are dunder methods?

Methods with double underscores, like __init__. Python calls them automatically so your objects work with built-in syntax.

MethodCalled byPurpose
__repr__repr(obj), the consoledeveloper-friendly text
__str__print(obj), str(obj)user-friendly text
__eq__a == bequality
__lt__a < b, sorted()ordering
__add__a + baddition
__len__len(obj)size
__getitem__obj[i]indexing
__contains__x in objmembership
__iter__for x in objiteration

💡 If you write only one, write __repr__. print() falls back to it when __str__ is missing.

⚠️ If you define __eq__, objects become unhashable unless you also define __hash__ (or use a frozen dataclass).

▶️ Runs in the app.

Example

Python
class Vector:
    def __init__(self, x, y):
        self.x, self.y = x, 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, self.y) == (other.x, other.y)

    def __abs__(self):
        return (self.x ** 2 + self.y ** 2) ** 0.5

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

v = Vector(1, 2) + Vector(3, 4)
print(v)                          # Vector(4, 6)
print(v * 2)                      # Vector(8, 12)
print(abs(Vector(3, 4)))          # 5.0
print(Vector(1, 1) == Vector(1, 1))   # True