python 3:如何检查对象是否是函数?

max*_*max 12 python class function python-3.x

我是否正确假设所有函数(内置或用户定义)都属于同一个类,但默认情况下该类似乎没有绑定到任何变量?

如何检查对象是否为函数?

我猜这可以做到:

def is_function(x):
  def tmp()
    pass
  return type(x) is type(tmp)
Run Code Online (Sandbox Code Playgroud)

它似乎并不整洁,我甚至不能100%确定它是完全正确的.

dan*_*rth 15

在python2中:

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

在python3中:

isinstance(fn, collections.Callable)
Run Code Online (Sandbox Code Playgroud)

因为Callable是一个抽象基类,这相当于:

hasattr(fn, '__call__')
Run Code Online (Sandbox Code Playgroud)

  • `callable`函数首先在Python 3.0中删除,然后在Python 3.2中恢复 - 所以如果使用最新版本的解释器,你也可以使用它与Python 3.有关详细信息,请参阅http://docs.python.org/3/library/functions.html?highlight=callable#callable. (6认同)

pyf*_*unc 5

如何检查对象是否为函数?

这与检查可调用对象不一样吗

hasattr(object, '__call__')
Run Code Online (Sandbox Code Playgroud)

以及在 python 2.x 中

callable(object) == True
Run Code Online (Sandbox Code Playgroud)