There are two easy and commonly-used ways to create callable objects in Python, which are as follows:
- By using the def statement to create a function.
- By creating an instance of a class that implements the _call()_ method. This can be done by using collections.abc.Callable as its base class.
Beyond these two, we can also assign a lambda form to a variable. A lambda is a small, anonymous function that consists of exactly one expression. We'd rather not emphasize saving lambdas in a variable, as this leads to the confusing situation where we have a function-like callable that's not defined with a def statement.
The following is a simple callable object, pow1, created from a class:
from typing import Callable
IntExp = Callable[[int, int], int]
class Power1:
def __call__(self, x: int, n: int) -> int:
p = 1
for i in range(n):
...