Understanding Python __call__ and __init__ Magic Methods and Their Use in Class Decorators
This article explains the differences between Python's __init__ and __call__ magic methods, demonstrates their behavior with example code, and shows how __call__ can be used to implement class decorators for callable objects.
In this article, the author explains the difference between Python's __init__ and __call__ magic methods, demonstrates their behavior with example code, and shows a practical use case of __call__ in implementing class decorators.
First, a simple class Person is defined with both __init__ and __call__ methods; creating an instance prints "init" once, while calling the instance repeatedly prints "call". The output illustrates that __init__ runs only during object construction, whereas __call__ enables the instance to be invoked like a function.
class Person:
def __init__(self):
print("init")
def __call__(self):
print("call")
m1 = Person()
m1()
m1()
m1()The printed result is:
init
call
call
callThe article then lists the key distinctions: __init__ is the constructor called once per instance, and __call__ makes the object callable, allowing custom behavior on each call. Attempting to call an object without __call__ raises a TypeError :
TypeError: 'Person' object is not callable
Finally, a class decorator example is presented: a MyDecorator class defines __init__ to store a function and __call__ to execute it, printing messages before and after. Applying @MyDecorator to a function hello shows how the decorator runs its __init__ once and __call__ on each function invocation.
class MyDecorator(object):
def __init__(self, f):
self.f = f
print("__init__()...")
def __call__(self):
print("__call__()...")
self.f()
@MyDecorator
def hello():
print("hello...")
hello()
hello()
hello()The printed result is:
__init__()...
__call__()...
hello...
__call__()...
hello...
__call__()...
hello...The author invites readers to share feedback and suggests that more detailed topics like class decorators could be covered in future posts.
IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.