【问题标题】:python find the type of a functionpython查找函数的类型
【发布时间】:2019-05-29 06:46:24
【问题描述】:

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

【问题讨论】:

  • 您已经通过使用type 获得了它的类型。没有绑定到该类型的function 内置变量;类知道自己的名称并不意味着存在具有该名称的变量。
  • 以防万一,您希望 Python 也返回函数的结果类型:这在动态语言中是不可能的,因为不同的 Returns 可能返回不同类型的结果。 Python 3 的 function annotations 可能会为您提供帮助,但它们并未强制执行。

标签: python class types


【解决方案1】:

检查函数类型的pythonic方法是使用isinstance builtin。

i = 2
type(i) is int #not recommended
isinstance(i, int) #recommended

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.

但是,请注意,它会为内置函数打印 false。如果您也希望包括这些,请检查如下

isinstance(f, (types.FunctionType, types.BuiltinFunctionType))

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

callable(f)

【讨论】:

  • 当然可以,只要def f(): pass; function = type(f)
  • 一个聪明的技巧。 @juanpa.arrivillaga 我想发布一个没有变通办法的经典答案,但这肯定也有效。 (需要注意的是,它的行为类似于types.FunctionType,因为它对内置函数的计算结果为 false。)编辑:因为正如 Juanpa 所指出的那样。
  • 它的行为不像像它,它 types.FunctionType
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-09
  • 2011-11-24
  • 1970-01-01
  • 1970-01-01
  • 2013-03-14
  • 2011-04-20
  • 1970-01-01
相关资源
最近更新 更多