__call__ in Python
Hello there! In this story, we will discuss how to use __call__
in Python classes. With __call__
, you can use class objects as functions, which means you first initialize the object and then use it as a function. Essentially, it makes your object callable (all methods in Python are callable objects!).
Let’s take a look at an example:
class MyClass:
def __call__(self):
print('hi')
my_object = MyClass()
my_object()
It will print hi
in the console. Let’s take a look at a more complex example.
import secrets
class TokenUrlsafeGenerator:
length: int
def __init__(self, length: int):
self.length = length
def __call__(self) -> str:
return secrets.token_urlsafe(self.length)
token_generator = TokenUrlsafeGenerator(length=32)
token = token_generator()
Let’s break this example down to understand how the code works:
First of all, you can use the secrets
module in Python. You can refer to the Python documentation for more details, but in short, this module will help you generate secure and random numbers or strings to manage the secrets of your project.
You can see the TokenUrlsafeGenerator
class, which is initialized with a length
argument. The __call__
method is used to generate the token based on this length. To generate secure tokens, we simply need to create an instance of this class and call it. It's as simple as that!
You can pass arguments to __call__
just like the other functions in Python. See the following example:
class Adder:
def __call__(self, arg1, arg2):
return arg1 + arg2
adder = Adder()
result = adder(1, 2)
In this example, the variable result
will have a value of 3
.
Conclusion
In this story, we learned how to convert a Python object into a callable one by using the __call__
method. This method provides us with the full functionality of functions in Python.
Hope you enjoy!