The Wayback Machine - https://web.archive.org/web/20250201204805/https://www.geeksforgeeks.org/__call__-in-python/
Open In App

__call__ in Python

Last Updated : 01 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 the instance is called as a function; if this method is defined,

x(arg1, arg2, ...)

is a shorthand for

x.__call__(arg1, arg2, ...)

.

object() is shorthand for object.__call__()

Example 1:

Python3 1==
class Example:
    def __init__(self):
        print("Instance Created")
    
    # Defining __call__ method
    def __call__(self):
        print("Instance is called via special method")

# Instance created
e = Example()

# __call__ method will be called
e()

Output :

Instance Created
Instance is called via special method

Example 2:

Python3 1==
class Product:
    def __init__(self):
        print("Instance Created")

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

# Instance created
ans = Product()

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

Output :

Instance Created
200

__call__ in Python – FAQs

How to make an instance of a class callable using __call__?

To make an instance of a class callable, you need to implement the __call__ method in your class. This special method allows you to use the instance as if it were a function. When you call an instance, the __call__ method is invoked with the provided arguments.

Example:

class MyCallableClass:
def __call__(self, *args, **kwargs):
print(f"Called with arguments: {args} and keyword arguments: {kwargs}")

obj = MyCallableClass()
obj(1, 2, 3, a=4, b=5)
# Output: Called with arguments: (1, 2, 3) and keyword arguments: {'a': 4, 'b': 5}

Can we provide an example of a class with a __call__ method?

Yes, here is a simple example of a class with the __call__ method:

Example:

class Adder:
def __init__(self, increment):
self.increment = increment

def __call__(self, number):
return number + self.increment

add_five = Adder(5)
result = add_five(10) # Calls the __call__ method
print(result) # Output: 15

In this example, Adder adds a specified increment to a number, and the __call__ method is used to perform the addition.

What are common use cases for the __call__ method?

Common use cases for the __call__ method include:

  • Function Objects: Creating objects that can be called like functions. For example, creating a function that maintains state across calls.
  • Decorators: Implementing decorators as classes where __call__ defines the wrapping logic.
  • Callbacks: Defining objects that act as callbacks or handlers.
  • Command Pattern: Encapsulating commands and actions within objects that can be executed with a call.

How to pass arguments to the __call__ method?

Arguments can be passed to the __call__ method in the same way as you would pass arguments to a regular function. The __call__ method accepts *args and **kwargs to handle positional and keyword arguments.

Example:

class Multiplier:
def __init__(self, factor):
self.factor = factor

def __call__(self, value):
return value * self.factor

double = Multiplier(2)
result = double(10) # Calls __call__ with 10
print(result) # Output: 20

Can the __call__ method have default arguments?

Yes, the __call__ method can have default arguments just like any other method. You can specify default values for parameters to make some arguments optional.

Example with default arguments:

class Greeter:
def __init__(self, greeting):
self.greeting = greeting

def __call__(self, name="World"):
return f"{self.greeting}, {name}!"

greet = Greeter("Hello")
print(greet()) # Output: Hello, World!
print(greet("Alice")) # Output: Hello, Alice!


Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg