Is Python supposed to be a type before trying to determine if it is a function?

In Python, the int character is used both in type and inline function. But when I use int in REPL or request its type, REPL tells me that it is a type.

 >>> int <type 'int'> >>> type(int) <type 'type'> 

This is good, but int also a built-in function: it is listed in the built-in functions table directly in the Python documentation .

Other built-in functions are reported in REPL:

 >>> abs <built-in function abs> >>> type(abs) <type 'builtin_function_or_method'> 

But I cannot get type to show me this for int . Now I can use int as a function if I want (sorry to use map instead of understanding, I'm just trying to make a point):

 >>> map(int, ["4", "2"]) [4, 2] 

So, Python knows how to use this function. But why does type choose a type over a function? Nothing in the definition of a type function is expected to expect this. And then, as a continuation, what is the meaning of this expression:

 id(int) 

This gives me an id type or function. I expect the first. Now, if this is the first, how would I get the identifier of the int function?

+6
source share
1 answer

There is only one thing called int , and only one thing is called abs .

The difference is that int is a class and abs is a function. Both of them, however, are callable. When you call int(42) , which calls the constructor of the int class, returning an instance of the int class.

This is not much different from:

 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 instantiate the class.

Once you understand this, the rest will follow.

+4
source

Source: https://habr.com/ru/post/971184/


All Articles