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

ยท

1 min read

Table of contents

No heading

No headings in the article.

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

ย