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.
Likely follow-ups
What's the difference between __str__ and __repr__?
__str__ should return a readable, user-facing string (used by print() and str()), while __repr__ should return an unambiguous, ideally eval-able representation useful for debugging (used by the REPL and repr()). If __str__ is not defined, Python falls back to __repr__ for str() and print().
In a debugging session, a list of custom objects printed in the console shows each item's __repr__, making it crucial to implement a clear, informative __repr__ for every domain model class.
Likely follow-ups
What does Python use when only __repr__ is defined?
Defining __add__(self, other) lets instances of your class respond to the + operator, and similarly __sub__, __mul__, __truediv__, etc. for other operators. Python calls left.__add__(right) first; if that returns NotImplemented, it tries right.__radd__(left) as a fallback, supporting mixed-type operations.
If two objects are equal (__eq__ returns True), they must have the same hash value so they behave consistently in sets and dict keys. By default, defining __eq__ without __hash__ makes the class unhashable (Python sets __hash__ to None automatically), which raises TypeError if you try to put instances in a set or use them as dict keys.
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __eq__(self, other):
return (self.x, self.y) == (other.x, other.y)
def __hash__(self):
return hash((self.x, self.y))
{Point(1,2)} # works because __hash__ is defined
Real-world example
A caching layer uses custom key objects as dict keys, so their class must define both __eq__ and __hash__ consistently or lookups will fail unpredictably.
Likely follow-ups
Why does Python disable __hash__ when __eq__ is overridden?
__enter__(self) runs at the start of a with block and its return value is bound to the as target. __exit__(self, exc_type, exc_val, exc_tb) runs on block exit, receiving exception info if one occurred; returning True suppresses the exception, while returning False (or None) lets it propagate normally.
class Transaction:
def __enter__(self):
print('BEGIN')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type:
print('ROLLBACK')
return False
print('COMMIT')
with Transaction():
print('doing work')
Real-world example
A database Transaction class uses __enter__/__exit__ to automatically COMMIT on success and ROLLBACK if any exception occurs inside the with block, without repeating try/finally everywhere.
Likely follow-ups
How does contextlib.contextmanager simplify writing this?
What happens if __exit__ itself raises an exception?
Defining __call__(self, *args, **kwargs) makes instances callable with parentheses, e.g., obj(x, y), which Python translates to obj.__call__(x, y). This is used for stateful callables like decorators-as-classes, memoized functions, or configurable strategy objects that need to remember state between calls.
class Multiplier:
def __init__(self, factor):
self.factor = factor
def __call__(self, x):
return x * self.factor
double = Multiplier(2)
print(double(5)) # 10 -- called like a function
Real-world example
A machine learning preprocessing pipeline defines transform classes with __call__ so each transform can be applied like a function while still holding configuration state (e.g., normalization parameters).
Likely follow-ups
How does __call__ enable class-based decorators?
What's the performance difference vs a plain function?
__new__(cls, ...) is a static method that actually creates and returns the new instance (allocating memory), called before __init__. __init__(self, ...) then initializes that already-created instance and returns None. You override __new__ for cases __init__ can't handle: controlling instance creation for immutable types (like subclassing tuple or str), implementing singletons, or returning an instance of a different class.
class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
a, b = Singleton(), Singleton()
print(a is b) # True
Real-world example
A configuration manager implements __new__ to enforce a single shared instance across the entire application, ensuring all code reads the same in-memory config object.
Likely follow-ups
Why can't __init__ alone implement a singleton reliably?
How does __new__ interact with immutable types like int subclasses?
Metaclasses & Class CustomizationMultiple Inheritance & MRO
Implementing these lets instances be compared with <, <=, >, >= respectively, which sorted() and list.sort() rely on by default (via < comparisons) when no key function is given. Using @functools.total_ordering, you can define just __eq__ and one of these to get all six comparison methods automatically.
__iadd__(self, other) implements the += operator and can mutate self in place and return self, avoiding creating a new object (unlike __add__, which must return a new object). If __iadd__ isn't defined, Python falls back to __add__ followed by reassignment (x = x + y), which is less efficient for mutable, resizable containers.
class Bag:
def __init__(self, items=None):
self.items = items or []
def __iadd__(self, other):
self.items.extend(other)
return self # mutate and return self
b = Bag([1,2])
b += [3,4]
print(b.items) # [1,2,3,4]
Real-world example
A custom mutable Matrix class implements __iadd__ so accumulating large matrices with += avoids allocating a brand-new matrix object on every update, improving performance in tight loops.
Likely follow-ups
What happens if __iadd__ returns a different object than self?
Why do immutable types typically not define __iadd__?
Data Types & StructuresMemory Management & Garbage Collection