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:
class Example:
def __init__( self ):
print ( "Instance Created" )
def __call__( self ):
print ( "Instance is called via special method" )
e = Example()
e()
|
Output :
Instance Created
Instance is called via special method
Example 2:
class Product:
def __init__( self ):
print ( "Instance Created" )
def __call__( self , a, b):
print (a * b)
ans = Product()
ans( 10 , 20 )
|
Output :
Instance Created
200
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
27 Feb, 2020
Like Article
Save Article