bhylu.com

Advertisements

__call__

__call__ makes an instance callable. It is useful when an operation needs configured state while presenting a function-like interface.

Understand the idea

The object's initializer stores configuration, and calling the instance performs the operation with current arguments. A closure can solve a similar problem; choose the representation that makes state, testing, and lifecycle easiest to understand. Do not add callable behaviour to an object if the action would be ambiguous to its users.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

class AddDelivery:
    def __init__(self, fee_cents):
        self.fee_cents = fee_cents
    def __call__(self, subtotal_cents):
        return subtotal_cents + self.fee_cents

with_delivery = AddDelivery(300)
print(with_delivery(1500))

Read the result

The result is 1800 cents. The configured delivery fee is retained by the callable instance.

Try one change

Create two configured instances with different fees and show that they remain independent.