python查找函数的类型
我有一个变量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
使用fa函数,我尝试使用u =
str(type(f))将type(f)的返回值转换为字符串。但是当我尝试u.print()时,我收到一条错误消息。这给我提出了另一个问题。在Unix下,来自Python的错误消息会出现在stderr或stdout上吗?
-
检查函数类型的pythonic方法是使用
isinstance
内置函数。i = 2 type(i) is int #not recommended isinstance(i, int) #recommended
Python包括一个
types
用于检查功能的模块。它还定义了标准Python解释器使用的某些对象类型的名称,但没有像int或str are这样的内置函数公开。
因此,要检查对象是否为函数,可以按以下方式使用类型模块
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)