Sobes.tech
Junior — Middle

Can you explain what an object callable as a function, or a callable object, is?

sobes.tech AI

Answer from AI

A callable object in Python is an object that can be called like a function, meaning you can use parentheses with arguments: obj().

Objects are considered callable if they have a __call__ method defined.

Example:

class Multiplier:
    def __init__(self, factor):
        self.factor = factor
    def __call__(self, x):
        return x * self.factor

mul_by_3 = Multiplier(3)
print(mul_by_3(10))  # Outputs 30

Here, mul_by_3 is an object that behaves like a function, multiplying the input value by 3.

Callable objects are useful for creating objects with state that can be used as functions, for example, to configure call parameters.

Can you explain what an object callable as a… - sobes.tech