I have this program
a = 5
print("valor=", 5*a())
when executing it throws me this error:
Traceback (most recent call last):
File "/home/candid/PycharmProjects/scrapper2/scrapper.py", line 2, in <module>
print("valor=", 5*a())
TypeError: 'int' object is not callable
and I don't understand what I'm doing wrong.
Short explanation: Use
[]
to access an element of a collection. Use()
to call a function.In Python,
X
any object is callable when it can be used as a function callX()
, possibly receiving parameters and returning something.A numeric variable is not callable . It is not something that is defined; there is no code to execute behind that value.
Strings, lists, tuples, and dictionaries are also not callable , for the same reason.
Typically this error occurs when they are used
()
instead of[]
to access an element within a string, list, tuple, or dictionary.The following uses are correct (with
[]
):produces
But if you change them
[]
to()
throws error:
What objects are callable ?
Functions, generators, and any objects that define the magic method are callable
__call__
.Example: we have a class
Cliente
, which stores name and balance:we can create a client with
but we can't say
then the error appears
which says that the class
Cliente
is not callable , and therefore no object of that class is.To make it callable , we define the method
__call__
, with the following signatureNote that you always have to define it with those arguments, even if they are not used in a particular implementation. Otherwise, Python does not consider the class callable .
What is this method supposed to do? Whatever is appropriate to our application; For example, in a banking application, the most used method may be the customer balance query:
So, we redefine the class
Cliente
:now print the customer balance.
Note: This example is usually solved by defining a query function
but what's up! You have to give a simple example.
Implementing
__call__
is more of a matter of convenience when there is a particular method that you use frequently and you want to save yourself having to type the method name over and over again.How to know if an object is callable ?
There is the function
callable(objeto)
that returnsTrue
if the object is callable andFalse
otherwise: