In Python the symbol int
is used both as a type and a built-in function. But when I use int
in the REPL, or ask for its type, the REPL tells me it is a type.
>>> int
<type 'int'>
>>> type(int)
<type 'type'>
This is fine, but int
is also a built-in function: it is listed in the table of built-in functions right in the Python documentation.
Other built-in functions are reported like this in the REPL:
>>> abs
<built-in function abs>
>>> type(abs)
<type 'builtin_function_or_method'>
But I can't get type
to show me this for int
. Now clearly I can use int
as a function if I want to (sorry for using map
instead of a comprehension, I'm just trying to make a point):
>>> map(int, ["4", "2"])
[4, 2]
So Python knows to use the function. But why does type
pick the type over the function? Nothing in the definition of the type
function says to expect this. And then as a follow-up, what is the meaning of this expression:
id(int)
Is this giving me the id
of the type or the function. I expect the former. Now if it is the former, how would I get the id of the built-in function int
?
There is only one thing called int
and only one thing called abs
.
The difference is that int
is a class, and abs
is a function. Both, however, are callable. When you call int(42)
, that calls the int
class's constructor, returning an instance of class int
.
It's not really much different to:
class Int(object):
def __init__(self, init_val=0):
self.val = init_val
obj = Int(42)
print Int, type(Int), obj, type(obj)
Here, Int
is callable, and can be used to construct instances of the class.
Once you realise this, the rest will follow.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With