Data Model

Callable Objects

__call__ lets an instance behave like a function while keeping state.

A callable object starts as ordinary state stored on an instance.

Source

class Multiplier:
    def __init__(self, factor):
        self.factor = factor
        self.calls = 0

double = Multiplier(2)
print(double.factor)

Output

2
OBJECT__call__obj(...)
Defining __call__ makes any object callable; functions are just one shape that satisfies this protocol.

__call__ makes the instance usable with function-call syntax.

Source

class Multiplier:
    def __init__(self, factor):
        self.factor = factor
        self.calls = 0

    def __call__(self, value):
        self.calls += 1
        return value * self.factor

double = Multiplier(2)
print(double(5))
print(double(7))

Output

10
14

Because the callable is still an object, it can remember state across calls.

Source

print(double.calls)

Output

2

Notes

See also

Run the complete example

Example code

Expected output

10
14
2

Execution time appears here after you run the example.