python 查找函数的类型

标签 python class types

我有一个变量 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/

相关文章:

python - 如何让 Python 使用 Assembly

python - 对聚合值进行聚合

python - 使用 Python 重命名 Python 代码中的变量

python - 从父类控制子类方法

php - 有什么方法可以在 PHP 中安全地重新声明一个类?

types - 有没有办法创建只接受一系列值的数据类型?

delphi - 函数的结果总是被初始化吗?

python - 以 newick 格式保存 NetworkX 树

php - 尝试获取列数据时,类返回整数而不是对象

python - Cython 中的 64 位整数