Search⌘ K
AI Features

Callable Objects

Explore how to make instances of Python classes callable by defining the __call__ method. Understand the difference between functions and callable objects, and learn how callable objects can maintain state to optimize performance and functionality.

We'll cover the following...

Overview

Just as functions are objects that can have attributes set on them, it is possible to create an object that can be called as though it were a function. Any object can be made callable by giving it a __call__() method that accepts the required arguments.

Example

Let’s make our Repeater class (Repeater_2), from the timer example, a little easier to use by making it a callable, as follows:

Python 3.10.4
class Repeater_2:
def __init__(self) -> None:
self.count = 0
def __call__(self, timer: float) -> None:
self.count += 1
format_time(f"Called Four: {self.count}")
...