Now that it\'s clear what a metaclass is, there is an associated concept that I use all the time without knowing what it really means.
I suppose everybody made once
A callable is anything that can be called.
The built-in callable (PyCallable_Check in objects.c) checks if the argument is either:
__call__
method orThe method named __call__
is (according to the documentation)
Called when the instance is ''called'' as a function
class Foo:
def __call__(self):
print 'called'
foo_instance = Foo()
foo_instance() #this is calling the __call__ method
Callable is a type or class of "Build-in function or Method" with a method call
>>> type(callable)
<class 'builtin_function_or_method'>
>>>
Example: print is a callable object. With a build-in function __call__ When you invoke the print function, Python creates an object of type print and invokes its method __call__ passing the parameters if any.
>>> type(print)
<class 'builtin_function_or_method'>
>>> print.__call__(10)
10
>>> print(10)
10
>>>
Thank you. Regards, Maris
__call__
makes any object be callable as a function.
This example will output 8:
class Adder(object):
def __init__(self, val):
self.val = val
def __call__(self, val):
return self.val + val
func = Adder(5)
print func(3)
A Callable is an object that has the __call__
method. This means you can fake callable functions or do neat things like Partial Function Application where you take a function and add something that enhances it or fills in some of the parameters, returning something that can be called in turn (known as Currying in functional programming circles).
Certain typographic errors will have the interpreter attempting to call something you did not intend, such as (for example) a string. This can produce errors where the interpreter attempts to execute a non-callable application. You can see this happening in a python interpreter by doing something like the transcript below.
[nigel@k9 ~]$ python
Python 2.5 (r25:51908, Nov 6 2007, 15:55:44)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 'aaa'() # <== Here we attempt to call a string.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
>>>
It's something you can put "(args)" after and expect it to work. A callable is usually a method or a class. Methods get called, classes get instantiated.
To check function or method of class is callable or not that means we can call that function.
Class A:
def __init__(self,val):
self.val = val
def bar(self):
print "bar"
obj = A()
callable(obj.bar)
True
callable(obj.__init___)
False
def foo(): return "s"
callable(foo)
True
callable(foo())
False