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.
| Method | Called by | Purpose |
|---|---|---|
__repr__ | repr(obj), the console | developer-friendly text |
__str__ | print(obj), str(obj) | user-friendly text |
__eq__ | a == b | equality |
__lt__ | a < b, sorted() | ordering |
__add__ | a + b | addition |
__len__ | len(obj) | size |
__getitem__ | obj[i] | indexing |
__contains__ | x in obj | membership |
__iter__ | for x in obj | iteration |
💡 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
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