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!
Similar Reads
__call__ in Python
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
3 min read
callable() in Python
In this article, we will see how to check if an object is callable in Python. In general, a callable is something that can be called. This built-in method in Python checks and returns True if the object passed appears to be callable, but may not be, otherwise False. Python callable()In Python, calla
3 min read
eval in Python
Python eval() function parse the expression argument and evaluate it as a Python expression and runs Python expression (code) within the program. Python eval() Function SyntaxSyntax: eval(expression, globals=None, locals=None) Parameters: expression: String is parsed and evaluated as a Python expres
6 min read
Python __all__
Have you ever used a Python fileâs variables after importing (`from F import *`) it into another Python file? In this scenario, every variable from that file can be used in the second file where the import is made. In this article, we'll look at one Python mechanism, called __all__, which allows use
5 min read
exec() in Python
exec() function is used for the dynamic execution of Python programs which can either be a string or object code. If it is a string, the string is parsed as a suite of Python statements which is then executed unless a syntax error occurs and if it is an object code, it is simply executed. We must be
4 min read
ascii() in Python
In Python, we have ascii() function that returns a string containing a printable representation of an object. In this article, we will see about ascii() in Python. Python ascii() FunctionPython ascii() function returns a string containing a printable representation of an object and escapes the non-A
3 min read
call() decorator in Python
Python Decorators are important features of the language that allow a programmer to modify the behavior of a class. These features are added functionally to the existing code. This is a type of metaprogramming when the program is modified at compile time. The decorators can be used to inject modifie
3 min read
Decorators in Python
In Python, decorators are a powerful and flexible way to modify or extend the behavior of functions or methods, without changing their actual code. A decorator is essentially a function that takes another function as an argument and returns a new function with enhanced functionality. Decorators are
10 min read
self in Python class
Self represents the instance of the class. By using the "self" we can access the attributes and methods of the class in Python. It binds the attributes with the given arguments. The reason you need to use self. is because Python does not use the @ syntax to refer to instance attributes. Python decid
6 min read
__init__ in Python
Prerequisites - Python Class and Objects, Self __init__ method in Python is used to initialize objects of a class. It is also called a constructor. It is like a default constructor in C++ and Java. Constructors are used to initialize the objectâs state. The task of constructors is to initialize (ass
5 min read