gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:39:43 24 4
gpt4 key购买 nike

我知道 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com