๐Ÿ” Unlock the Power of __call__ in Python! ๐Ÿ”

Rashid Ul HaqRashid Ul Haq
1 min read

Table of contents

We all know about the init function in Python, but have you ever encountered the call function? ๐Ÿค” This special method can turn instances of your class into callable objects, making them act like functions!
Let's dive into an example to see this in action. ๐Ÿ‘‡

class Counter:
    def __init__(self):
        self.count = 0

    def __call__(self):
        self.count += 1
        return self.count

# Create an instance of the Counter class

counter = Counter()

# Call the instance like a function
print(counter())  # Output: 1

In this code, counter() is actually calling the call method behind the scenes! ๐Ÿ”ฎ Every time we call counter(), the count increments by 1.
It is often used in libraries and books, for example, in the spaCy [1] source code and Django validators.
References
[1] spaCy source code

[2] Django validators

0
Subscribe to my newsletter

Read articles from Rashid Ul Haq directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Rashid Ul Haq
Rashid Ul Haq

I am a passionate AI and machine learning expert with extensive experience in deep learning, TensorFlow, and advanced data analytics. Having completed numerous specializations and projects, I have a wealth of knowledge and practical insights into the field. I am sharing my journey and expertise through detailed articles on neural networks, deep learning frameworks, and the latest advancements in AI technology.