EnT*_*Cas 13 python reflection inspection
我正在玩Python可调用.基本上,您可以定义python类并实现__call__方法,以使此类的实例可调用.例如,
class AwesomeFunction(object):
def __call__(self, a, b):
return a+b
Run Code Online (Sandbox Code Playgroud)
模块检查有一个函数getargspec,它为您提供函数的参数规范.但是,我似乎无法在可调用对象上使用它:
fn = AwesomeFunction()
import inspect
inspect.getargspec(fn)
Run Code Online (Sandbox Code Playgroud)
不幸的是,我得到了一个TypeError:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/inspect.py", line 803, in getargspec
raise TypeError('arg is not a Python function')
TypeError: arg is not a Python function
Run Code Online (Sandbox Code Playgroud)
我认为你不能将任何可调用对象视为函数是非常不幸的,除非我在这里做错了什么?
如果你看看svn.python.org上getargspec的inspect模块代码中的定义.您将看到它调用isfunction自己调用的内容:
isinstance(object, types.FunctionType)
Run Code Online (Sandbox Code Playgroud)
因为,你AwesomeFunction显然不是types.FunctionType它的一个实例失败.
如果您希望它工作,您应该尝试以下方法:
inspect.getargspec(fn.__call__)
Run Code Online (Sandbox Code Playgroud)