Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Classes and Special Methods

__call__()

Reference for Python __call__(): make instances callable like functions, keep state between calls, build decorators and use callable() to test.

When a class defines __call__(), its instances can be called like functions: obj(1, 2) runs type(obj).__call__(obj, 1, 2). This lets you combine function-style usage with state that lives on the object.

Callable objects are useful for configurable functions, counters and caches, stateful decorators, and strategy objects that must look like plain functions to the code using them.

Python
class Adder:
    def __init__(self, n):
        self.n = n
    def __call__(self, x):
        return x + self.n

add5 = Adder(5)
print(add5(10))   # 15

Try it

Python Callable instances with state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python A class-based decorator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
class C:
    def __call__(self, *args, **kwargs):
        ...

obj = C()
obj(1, 2, key=3)    # same as C.__call__(obj, 1, 2, key=3)
Part Description
self The instance being called.
*args, **kwargs Whatever the caller passes. Any signature is allowed.

Return value: whatever __call__() returns.

Raises: TypeError: 'X' object is not callable if the class has no __call__().

Usage notes

  • Looked up on the type. Python uses type(obj).__call__, so assigning obj.__call__ = ... on one instance does not make it callable (shown above).
  • Classes are callable too. Counter() works because the metaclass type defines __call__(), which runs __new__() and __init__().
  • callable(obj) returns True for functions, methods, classes and instances with __call__(). It cannot promise that a particular call will succeed.
  • State lives on the instance. That is the main advantage over a plain function, which would need a closure or a global.
  • Class-based decorators use __call__() as the wrapper. Use functools.update_wrapper(self, func) to copy the name and docstring. Such decorators do not bind as methods automatically unless you also implement __get__().
  • Alternatives. A closure (def make_adder(n): return lambda x: x + n) or functools.partial is lighter when no extra methods are needed.
  • Keep the signature meaningful. Avoid __call__(self, *args, **kwargs) unless forwarding; explicit parameters document the interface.
  • Async. async def __call__ makes await obj() work.