以调用它们的方式获取可调用对象的参数名称

时间:2015-12-22 15:39:04

标签: 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']

2 个答案:

答案 0 :(得分:3)

>>> 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) 个对象不是函数。它们的默认参数存储为单独的属性,以及原始的可调用属性。 Introspect 那些

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

方法是围绕作为第一个参数传递的函数的瘦包装器。实际的函数不会改变签名,唯一改变的是第一个参数自动传递给你。

建立一个&#39;泛型&#39;解决方案,您必须测试您拥有的对象的类型,打开方法或部分和特殊情况:

foo1

模拟您的X().foo2foo4>>> generic_get_args(foo1) ['a', 'b'] >>> generic_get_args(X().foo2) ['a', 'b'] >>> generic_get_args(foo4) ['a', 'b']

KieContainer kieContainer =
   kieServices.newKieContainer(kieServices.getRepository().getDefaultReleaseId() );
KieBase kieBase = kieContainer.getKieBase();
KieSession kieSession = kieBase.newKieSession();

答案 1 :(得分:1)

x.foo2是一个类成员,所以它有self(类实例)作为第一个参数(就像你指定的那样)。

顺便说一下,你可以在一个没有'self'的类中声明自由函数:

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

foo4不是Python意义上的函数,它是一个具有特定行为的类,而不是标准的Python函数。

相关问题