Skip to content

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

python
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

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary