1.

What is a callable object in Python?

Answer»

An object that can invoke a certain action or process is callable. The most obvious example is a function. Any function, built-in or user defined or a method in built-in or user defined class is an object of Function class

&GT;>> def myfunction(): print ('HELLO') >>> type(myfunction) <class 'function'> >>> type(print) <class 'builtin_function_or_method'>

Python’s standard library has a nuilt-in callable() function that returns true if object is callable. Obviously a function returns true.

>>> callable(myfunction) True >>> callable(print) True

A callable object with parentheses (having arguments or not) invokes associated functionality. In fact any object that has access to __call__() MAGIC method is callable. Above function is normally called by entering myfunction(). However it can also be called by using __call_() method inherited from function class

>>> myfunction.__call__() Hello >>> myfunction() Hello

Numbers, string, collection objects etc are not callable because they do not inherit __call__() method

>>> a=10 >>> b='hello' >>> c=[1,2,3] >>> callable(10) False >>> callable(b) False >>> callable(c) False

In Python, class is also an object and it is callable.

>>> class MyClass: def __init__(SELF): print ('called') >>> MyClass() called <__main__.MyClass object at 0x7f37d8066080> >>> MyClass.__call__() called

<__main__.MyClass object at 0x7f37dbd35710>

However, object of MyClass is not callable.

>>> m=MyClass() called >>> m() Traceback (most recent call last):  File "<pyshell#23>", LINE 1, in <module>    m() TypeError: 'MyClass' object is not callable

In order that object of user defined be callable, it must override __call__() method

>>> class MyClass: def __init__(self): print ('called') def __call__(self): print ('this makes object callable') >>> m=MyClass() called >>> m() this makes object callable


Discussion

No Comment Found