A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/__call__-in-python/ below:

__call__ in Python - GeeksforGeeks

__call__ in Python

Last Updated : 12 Jul, 2025

Python has a set of built-in methods and __call__ is one of them. The __call__ method enables Python programmers to write classes where the instances behave like functions and can be called like a function. When this method is defined, calling an object (obj(arg1, arg2)) automatically triggers obj.__call__(arg1, arg2). This makes objects behave like functions, enabling more flexible and reusable code.

Syntax:

class Example:
def __init__(self):
# code

# Defining __call__ method


def __call__(self):
# code

Examples of __call__

Let's understand the implementation of __call__ in Python with the help of some code examples.

Example 1: Basic Usage

In this example, we will define a class and create a __call__ method in it and call it using the object of the that:

Python
class Gfg:
    def __init__(self):
        print("Instance Created")
    
    # Defining __call__ method
    def __call__(self):
        print("Instance is called via special method")

# Instance created
e = Gfg()

# __call__ method will be called
e()

Output
Instance Created
Instance is called via special method

Explanation:

Example 2: Passing Arguments

Now let's see how to pass arguments to such methods:

Python
class Prod:
    def __init__(self):
        print("Instance Created")

    # Defining __call__ method
    def __call__(self, a, b):
        print(a * b)

# Instance created
a = Prod()

# __call__ method will be called
a(10, 20)

Output
Instance Created
200

Explanation:

Example 3: Creating a Counter Function

Lets's create a counter object using __call__:

Python
class C:
    def __init__(self):
        self.count = 0

    def __call__(self):
        self.count += 1
        return self.count

count = C()
print(count()) 
print(count())  
print(count()) 

Exlpanation:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4