2 min read
In programming, a callable is something that can be called.
In Python, a callable is anything that can be called, using parentheses and maybe with some arguments. Functions, Generators, and Classes are inherently callable in Python.
callable() method takes an object and returns a boolean.
True- if the object is callable
False- if the object is not callable
callable() method checks if the object is either of the two -
tp_call(c struct) member.
Since functions are callable in Python.
def my_function(): print("Hi, I'm a function") callable(my_function)
This indicates that every time we create a function, Python creates a callable object for it. You can also verify the presence of
<method-wrapper '__call__' of function object at 0x7f08706d5840>
Similarly for a Class,
class MyClass(): def my_method(self): print("Hi, I am a class method") callable(MyClass)
However, if you create an object and run
callable() method over that then you will observe that class objects are not inherently callable in Python.
my_obj = MyClass() callable(my_obj)
If you try to call the object with parentisis you will get an error message saying object is not callble.
TypeError: 'MyClass' object is not callable
However, we can create classes having
__call__ method which makes instance of the class callable.
class MyClass(): def __call__(self): print("I am callable now") def my_method(self): print("Hi, I am a class method") my_obj = MyClass() callable(my_obj)
Now if you call the object the
__call__ method will run.
I am callable now
Latest from djangocentral