无法获得 Python 可调用对象的 argspec? [英] Can't get argspec for Python callables?
问题描述
我正在玩可调用的 Python.基本上你可以定义一个 python 类并实现 __call__
方法来使这个类的实例可调用.例如,
I'm playing with Python callable. Basically you can define a python class and implement __call__
method to make the instance of this class callable. e.g.,
class AwesomeFunction(object):
def __call__(self, a, b):
return a+b
模块检查有一个函数getargspec,它给你一个函数的参数说明.但是,似乎我不能在可调用对象上使用它:
Module inspect has a function getargspec, which gives you the argument specification of a function. However, it seems I cannot use it on a callable object:
fn = AwesomeFunction()
import inspect
inspect.getargspec(fn)
不幸的是,我遇到了类型错误:
Unfortunately, I got a 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
我认为您不能将任何可调用对象视为函数是非常不幸的,除非我在这里做错了什么?
I think it's quite unfortunate that you can't treat any callable object as function, unless I'm doing something wrong here?
推荐答案
如果你需要这个功能,写一个包装函数来检查fn
是否有一个属性__call__
,如果是,则将其 __call__
函数传递给 getargspec.
If you need this functionality, it is absolutely trivial to write a wrapper function that will check to see if fn
has an attribute __call__
and if it does, pass its __call__
function to getargspec.
这篇关于无法获得 Python 可调用对象的 argspec?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!