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)
如何检查对象是否为函数?
这与检查可调用对象不一样吗
hasattr(object, '__call__')
Run Code Online (Sandbox Code Playgroud)
以及在 python 2.x 中
callable(object) == True
Run Code Online (Sandbox Code Playgroud)