This Python __call__ lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.
__call__ lets you use an object as if it were a function. The object can store settings, and the call can run one action with those settings.
A normal method is easier to discover. Add __call__ only when the object has one obvious action.
Example 1: Start here
hello(\"Meera\") calls __call__. hello.city still reads the stored city.
class Greeter: # a template for objects
def __init__(self, city): # runs when you create the object
self.city = city # store this on the object
def __call__(self, name): # define the function; it runs when you call it
return name + " from " + self.city # send this value back to the caller
hello = Greeter("Chennai") # one object
print(hello("Meera"))
Example 2: Call an object
__call__ runs when you use the object like a function.
class Greeter: # a template for objects
def __init__(self, prefix): # runs when you create the object
self.prefix = prefix # store this on the object
def __call__(self, name): # define the function; it runs when you call it
return self.prefix + " " + name # send this value back to the caller
hello = Greeter("Hello") # one object
print(hello("Asha"))
Example 3: Remember earlier calls
The object keeps state between calls.
class Counter: # a template for objects
def __init__(self): # runs when you create the object
self.count = 0 # store this on the object
def __call__(self): # define the function; it runs when you call it
self.count += 1 # update the stored value
return self.count # send this value back to the caller
tick = Counter() # one object
print(tick())
print(tick())
Example 4: A normal function is simpler
Use __call__ when the object needs to remember something between calls.
def greet(name): # define the function; it runs when you call it
return "Hello " + name # send this value back to the caller
print(greet("Asha"))
