我有一个变量 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
使用 f 函数,我尝试将 type(f) 的返回值转换为字符串,其中 u = str(type(f))。但是当我尝试 u.print() 时,我收到一条错误消息。这对我提出了另一个问题。在 Unix 下,来自 Python 的错误消息是否出现在 stderr 或 stdout 上?
最佳答案
检查函数类型的pythonic方法是使用 isinstance
内置。
i = 2
type(i) is int #not recommended
isinstance(i, int) #recommended
Python 包含一个
types
用于检查功能等的模块。It also defines names for some object types that are used by the standard Python interpreter, but not exposed as builtins like int or str are.
所以,要检查一个对象是否是一个函数,你可以使用 types 模块如下
def f():
print("test")
import types
type(f) is types.FunctionType #Not recommended but it does work
isinstance(f, types.FunctionType) #recommended.
但是,请注意,它会为内置函数打印 false。如果您还想包括这些,请检查以下内容
isinstance(f, (types.FunctionType, types.BuiltinFunctionType))
但是,如果您只需要特定的功能,请使用上述内容。最后,如果您只关心检查它是否是函数、可调用或方法之一,那么只需检查它的行为是否像可调用。
callable(f)
关于python 查找函数的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54009407/