Sobes.tech
Middle

What are the __call__ methods in Python and how do they work?

sobes.tech AI

Answer from AI

The __call__ method allows class instances to be callable objects, like functions. When an instance of a class with a defined __call__ method is called using parentheses (), the code of this method is executed.

Example:

# Class with a __call__ method
class CallableObject:
    def __init__(self, name):
        self.name = name

    def __call__(self, greeting):
        # The __call__ method accepts arguments
        return f"{greeting}, {self.name}!"

# Create an instance of the class
obj = CallableObject("World")

# Call the instance as a function
result = obj("Hello")
print(result)