Course contentsShow
← Python
Lesson 457 of 1,0607. Object-Oriented ProgrammingFree lesson

Implementing Callable Object Instances

Define the __call__ method to allow your class instances to be invoked like functions, enabling the creation of stateful function objects.

Implementing Callable Object Instances

In this lesson, you will learn how to make your class instances behave just like functions by using the __call__ magic method.

The Power of __call__

Normally, when you create an instance of a class, you access its methods using dot notation, like my_object.do_something(). However, Python allows you to make an object "callable"—meaning you can invoke it directly using parentheses, like my_object().

To enable this, you implement the __call__ method within your class. This is incredibly useful when you want to create an object that maintains internal state but acts like a function. For example, consider a "Multiplier" class that remembers a specific number to multiply others by:

class Multiplier:
    def __init__(self, factor):
        self.factor = factor

    def __call__(self, number):
        return number * self.factor

# Create an instance that doubles values
double = Multiplier(2)

# Now use the instance like a function
print(double(5))  # Output: 10
print(double(10)) # Output: 20

Why use this?

In the example above, the Multiplier object is a "stateful function." While a regular function would need you to pass the factor every time, our Multiplier instance "remembers" the factor that was set during initialization.

The __call__ method can accept any arguments you define, just like a standard method. When you write double(5), Python translates that under the hood to double.__call__(5). This pattern is widely used in decorators, event handlers, and data processing pipelines where you need an object to hold configuration settings or data, but also provide a clean, function-like interface for the user.

By using __call__, you bridge the gap between static data (the object's attributes) and dynamic execution (the function logic), providing a seamless experience for those using your classes.

Key Takeaway: By defining the __call__ method in your class, you transform your objects into callable instances, allowing them to maintain state while being invoked with the same syntax as a standard function.