python3中的函数类型是什么

Zer*_*ays 10 python python-3.x

在python 3中,每个东西都是objs,函数也是如此.函数是一等公民,这意味着我们可以像其他变量一样做.

>>> class x:
    pass

>>> 
>>> isinstance(x,type)
True
>>> type(x)
<class 'type'>
>>> 
>>> x=12
>>> isinstance(x,int)
True
>>> type(x)
<class 'int'>
>>> 
Run Code Online (Sandbox Code Playgroud)

但功能不同!:

>>> def x():
    pass

>>> type(x)
<class 'function'>
>>> isinstance(x,function)
Traceback (most recent call last):
  File "<pyshell#56>", line 1, in <module>
    isinstance(x,function)
NameError: name 'function' is not defined
>>>
Run Code Online (Sandbox Code Playgroud)

为什么错误?什么是python函数类型?

fal*_*tru 9

你可以使用types.FunctionType:

>>> def x():
...     pass
...
>>> import types
>>> isinstance(x, types.FunctionType)
True
Run Code Online (Sandbox Code Playgroud)


Ana*_*mar 5

@falsetru 的答案对于函数的类型是正确的。

但是,如果您要查找的是检查是否可以使用某个特定对象来调用(),那么您可以使用内置函数callable()。例子 -

>>> def f():
...  pass
...
>>> class CA:
...     pass
...
>>> callable(f)
True
>>> callable(CA)
True
>>> callable(int)
True
>>> a = 1
>>> callable(a)
False
Run Code Online (Sandbox Code Playgroud)