📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials Python from Zero Magic Methods

Magic Methods

6 min read
Magic methods customise object behaviour. __repr__ defines the debug string, __str__ the display string, __len__ makes len() work, and __eq__ defines equality. They make your classes feel like built-in types.

Dunder / Magic Methods

class Vector:
    def __init__(self, x, y):
        self.x, self.y = x, y
    def __repr__(self):
        return f"Vector({self.x}, {self.y})"
    def __add__(self, other):
        return Vector(self.x+other.x, self.y+other.y)
    def __len__(self):
        return 2

v = Vector(1, 2) + Vector(3, 4)
print(v)       # Vector(4, 6)
print(len(v))  # 2