Magic Method
In one line
Magic methods are __dunder__ methods that let your objects work with Python operators (+, len(), str(), etc.).
In simple words
Magic methods (also called dunder methods for their double-underscore names) let you define how your custom objects interact with Python's built-in operations and operators.
Common ones:
__init__— constructor__str__/__repr__— string representation__eq__,__lt__— comparisons__add__,__mul__— arithmetic operators__len__,__getitem__— container protocol__enter__/__exit__— context managers__iter__/__next__— iteration
You don't call these directly — Python calls them when you use operators or built-in functions on your objects.
Example
class Vector:
def __init__(self, x, y):
self.x = x
self.y = 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 __abs__(self):
return (self.x ** 2 + self.y ** 2) ** 0.5
v1 = Vector(3, 4)
v2 = Vector(1, 2)
print(v1 + v2) # Vector(4, 6) — uses __add__
print(abs(v1)) # 5.0 — uses __abs__Magic methods make custom objects work with +, abs(), print(), etc. Python calls them implicitly — you rarely call them directly.
Common confusions
Confused with: regular method
The difference: Magic methods have __dunder__ names and are called implicitly by Python operators/built-ins (v1 + v2 calls __add__). Regular methods are called explicitly by name (obj.method()). You should never call magic methods directly.
Related terms
Related Resources
Related Lessons
- Python OOP
Magic methods.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.