The __call__()
method enables class objects to be called like functions. When the method is defined for an object, the object can be considered as a "callable object".
Some familiar objects that have this method defined by default includes, functions, lambda functions and classes. This is the method that actually gets invoked when you call such objects by writing their name with parenthesis.
Calling the __call__() method with a class will result with a class object being instantiated. For example:
Defining the __call__() method for custom objects
Class object are not callable by default, if you want them to be callable, you must define the __call__() method for the objects.
def __call__(self, [, args...]): #imethod body
copy
Like all other instance methods, the __call__()
method must include the self
parameter in its definition.
The function can also include any other necessary parameters(alongside self
) that should be given as arguments when the object is being called.
Whenever an object contains this method, calling the builtin function, callable() with the object returns True
.
You have now learned how you can make your custom objects callable.