python - 以调用方式获取可调用对象的参数名称

标签 python function

我知道 inspect.getargspec 可用于获取函数参数的名称:

>>> from inspect import getargspec
>>> def foo1(a, b):
...     pass
...
>>> getargspec(foo1).args
['a', 'b']

但下面不是我所期望的:

>>> class X(object):
...     def foo2(self, a, b):
...         pass
...
>>> x = X()
>>> getargspec(x.foo2).args
['self', 'a', 'b']

还有:

>>> from functools import partial
>>> def foo3(a, b, c):
...     pass
...
>>> foo4 = partial(foo3, c=1)
>>> getargspec(foo4).args
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\inspect.py", line 816, in getargspec
    raise TypeError('{!r} is not a Python function'.format(func))
TypeError: <functools.partial object at 0x000000000262F598> is not a Python function

如何让 foo1x.foo2foo4 都返回 ['a', 'b']?

最佳答案

partial() 对象不是函数。它们的默认参数存储为单独的属性,以及原始的可调用对象。反省那些:

>>> from functools import partial
>>> def foo3(a, b, c):
...     pass
...
>>> foo4 = partial(foo3, c=1)
>>> foo4.args, foo4.keywords
((), {'c': 1})
>>> from inspect import getargspec
>>> getargspec(foo4.func)
ArgSpec(args=['a', 'b', 'c'], varargs=None, keywords=None, defaults=None)

方法是将实例作为第一个参数传入的函数的薄包装器。实际函数不会改变签名,唯一改变的是第一个参数会自动为您传递。

要构建“通用”解决方案,您必须测试您拥有的对象的类型、解包方法或部分和特殊情况:

def generic_get_args(callable):
    if {'args', 'keywords', 'func'}.issubset(dir(callable)):
        # assume a partial object
        spec = getargspec(callable.func).args[len(callable.args):]
        return [var for var in spec if var not in callable.keywords]
    if getattr(callable, '__self__', None) is not None:
        # bound method
        return getargspec(callable).args[1:]
    return getargspec(callable).args

针对您的 foo1X().foo2foo4 的演示:

>>> generic_get_args(foo1)
['a', 'b']
>>> generic_get_args(X().foo2)
['a', 'b']
>>> generic_get_args(foo4)
['a', 'b']

关于python - 以调用方式获取可调用对象的参数名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34419402/

相关文章:

python - 重新加载使用 'import foo as f' 导入的 f ?

python - 如何在 python 中搜索特定的 Outlook 电子邮件

python - 如何在 python couchdb 中过滤更改

javascript - 石头剪刀布javascript函数不显示结果

ios - Swift 函数 - 传递可选对象

python - Pandas - 使用定界符拆分文本

android - Buildozer,无法计算 sizeof (size_t)

javascript - MVC : Calling Javascript function in View without any HTML control

javascript - 访问 jquery 选择器内的函数

javascript - 你如何处理多参数 JavaScript 函数?