🐍 Python Intermediate

What is Python's __call__ method?

Answer

The __call__ method makes instances of a class callable — you can use them like functions: obj(args). Example: class Multiplier: def __init__(self, n): self.n = n; def __call__(self, x): return x * self.n. Use: double = Multiplier(2); double(5) returns 10. Check if callable: callable(obj). Use cases: function objects with state (like closures but as classes), decorators as classes, partial application, and function factories. Stateful callable classes are often more readable than closures for complex logic. Comparison: a class with __call__ is like a closure — it holds state between calls. functools.partial creates callables with pre-filled arguments. Django middleware, Werkzeug WSGI apps, and many frameworks use callable objects as middleware/handlers.