Python › Magic Methods & Operator Overloading

What are 'magic methods' (dunder methods) in Python, and why are they called that?

Beginner

Answer

Magic methods are special methods surrounded by double underscores (e.g., __init__, __str__, __add__) that Python calls implicitly in response to built-in operations like construction, printing, arithmetic, or comparisons. They're called 'dunder' methods (double underscore) and let custom classes integrate with Python's built-in syntax and functions.
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y
    def __repr__(self):
        return f'Point({self.x}, {self.y})'

p = Point(1, 2)
print(p)  # Point(1, 2) -- uses __repr__
Real-world example A custom Money class defines __add__, __eq__, and __repr__ so instances can be added and compared with natural + and == syntax instead of explicit method calls.

Common follow-ups: What's the difference between __str__ and __repr__?;Which dunder methods does len() rely on?