Python __call__(): Call Function with Dynamic Parameters – Python Tutorial

By | March 29, 2022

Python built-in function __call__() can make a class object callable like a function. Here is the tutorial:

Python __call__: Make a Class Instance Callable Like a Function – Python Tutorial

However, here is a problem: if the function parameters are changed, how to call it in __call__(). In this tutorial, we will discuss this topic.

Python __call__()

It is defined as:

def __call__(self, *args, **kwargs):

Here args and kwargs are dynamic parameters.

How to make __call() can call function with dynamic parameters

Here is an example:

class Test:
    def __call__(self, *args, **kwargs):
        self.forward(*args, **kwargs)

    def forward(self, n1, n2, name = "add"):
        print(n1, n2, name)

t = Test()
t(3, 4, "sub")
t(3, 4, name = "addx")

In this code, we use __call__() to call forward() function with *args, **kwargs.

Run this code, we will get:

3 4 sub
3 4 addx

We can find: parameters of forward() are changed, it can be called correctly by __call__().