python 查找函数的类型

Dav*_*ein 2 python types class

我有一个变量 f。我如何确定它的类型?这是我的代码,输入到 python 解释器中,显示使用我在 Google 上找到的许多示例的成功模式时出现错误。(提示:我对 Python 非常陌生。)

>>> i=2; type(i) is int
True
>>> def f():
...     pass
... 
>>> type(f)
<class 'function'>
>>> type(i)
<class 'int'>
>>> type(f) is function
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'function' is not defined
>>> f=3
>>> type(f) is int
True
Run Code Online (Sandbox Code Playgroud)

使用 fa 函数,我尝试将 type(f) 的返回值转换为字符串,其中 u = str(type(f))。但是当我尝试 u.print() 时,我收到一条错误消息。这对我提出了另一个问题。在 Unix 下,来自 Python 的错误消息会出现在 stderr 或 stdout 上吗?

Par*_*ngh 6

检查函数类型的 Pythonic 方法是使用isinstancebuiltin。

i = 2
type(i) is int #not recommended
isinstance(i, int) #recommended
Run Code Online (Sandbox Code Playgroud)

Python 包括一个types用于检查函数等的模块。

它还定义了标准 Python 解释器使用的某些对象类型的名称,但不会像 int 或 str 这样的内置函数公开。

所以,要检查一个对象是否是一个函数,你可以使用 types 模块如下

def f():
    print("test")    
import types
type(f) is types.FunctionType #Not recommended but it does work
isinstance(f, types.FunctionType) #recommended.
Run Code Online (Sandbox Code Playgroud)

但是,请注意,它会为内置函数打印 false。如果您还想包括这些,请检查以下内容

isinstance(f, (types.FunctionType, types.BuiltinFunctionType))
Run Code Online (Sandbox Code Playgroud)

但是,如果您只需要特定的功能,请使用上述内容。最后,如果您只关心检查它是否是函数、可调用或方法之一,那么只需检查它的行为是否像可调用。

callable(f)
Run Code Online (Sandbox Code Playgroud)

  • 当然,你可以只做 `def f(): pass; 函数 = 类型(f)` (3认同)
  • 它的行为不像*喜欢*,它**是**`types.FunctionType` (3认同)