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

By | December 17, 2021

Usually, after we have created a class instance in python, we will use instance.fun() to call a class function. For example:

class Person:
    def __init__(self, name):
        self.n = name

    def show_name(self):
        print(self.n)

m = Person("Tom")
m.show_name()

In this example code, ,we create a Person instance m, then we will use m.show_name() to display his name.

However, instance m is not callable, for example:

m = Person("Tom")
m("Tome")

Run this code, you will find this error:

    m("Tome")
TypeError: 'Person' object is not callable

How to make a python instance callable?

You may find this kind of python code:

python class instance is callable

In this code, self.backbone is a class instance, however, it is used like a python function.

In python, we can define a __call__ function in class to make a class instance callable.

Python __call__ function is defined as:

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

In order to understand args and kwargs, you can view this tutorial:

Understand Python **kwargs Parameter: A Beginner Guide

Understand Python *args Parameter: A Beginner Guide – Python Tutorial

Then we can use code below to make a python class instance callable.

class Person:
    def __init__(self, name):
        self.n = name

    def show_name(self):
        print(self.n)

    def __call__(self, *args, **kwargs):
        self.n = args[0]
        self.show_name()


m = Person("Tom")
m("Jack")
m("Lily")

Run this code, you will see this result:

Jack
Lily

You can find here class instance m is callable, you can use it like a function.

Leave a Reply

Your email address will not be published. Required fields are marked *