Python Glossary Русский

all Python 3Functionsterm

Callable objects __call__

callable

An object with a __call__ method can be called like a function. Used for stateful callables and for class-based decorators.

Syntax

class F:
    def __call__(self, x): ...
f = F()
f(10)

A class with __call__ is the alternative to a closure when state is better kept in attributes: it stays visible, mutable, and can carry helper methods (reset, __repr__), whereas a closure hides it. Use the built-in callable(obj) to test whether something can be called — and note that ordinary functions are themselves objects with a __call__.

Examples

class Adder:
    def __init__(self, n):
        self.n = n
    def __call__(self, x):
        return x + self.n
add5 = Adder(5)
print(add5(3))  # → 8
class Counter:
    def __init__(self):
        self.count = 0
    def __call__(self):
        self.count += 1
        return self.count
c = Counter()
print(c(), c(), c())  # → 1 2 3
class Multiplier:
    def __init__(self, factor):
        self.factor = factor
    def __call__(self, x):
        return x * self.factor
double = Multiplier(2)
print(list(map(double, [1,2,3,4])))  # → [2,4,6,8]
print(callable(double))  # → True
print(callable(42))     # → False
class Logger:
    def __init__(self, func):
        self.func = func
        self.calls = 0
    def __call__(self, *a, **kw):
        self.calls += 1
        return self.func(*a, **kw)
def add(a,b): return a+b
logged_add = Logger(add)
print(logged_add(1,2))  # → 3
print(logged_add.calls)  # → 1

See also

Open in the full glossarydocs.python.orgReport an inaccuracy