无法获得Python callables的argspec?

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)

我认为你不能将任何可调用对象视为函数是非常不幸的,除非我在这里做错了什么?

Ada*_*and 7

如果你需要这个功能,那么编写一个包装器函数是非常简单的,它将检查是否fn有属性__call__,如果有,则将其__call__函数传递给getargspec.


Moe*_*Moe 5

如果你看看svn.python.org上getargspecinspect模块代码中的定义.您将看到它调用isfunction自己调用的内容:

isinstance(object, types.FunctionType)
Run Code Online (Sandbox Code Playgroud)

因为,你AwesomeFunction显然不是types.FunctionType它的一个实例失败.

如果您希望它工作,您应该尝试以下方法:

inspect.getargspec(fn.__call__)
Run Code Online (Sandbox Code Playgroud)

  • 我知道它期待一种功能类型.我只是感叹Python并没有以统一功能和对象的方式进行设计. (5认同)