python - 如何获取方法参数名称?

给定 Python 函数:

def a_method(arg1, arg2):
    pass

如何提取参数的数量和名称。即,鉴于我有对 func 的引用,我希望 func.[something] 返回 ("arg1", "arg2").

这个使用场景是我有一个装饰器,我希望使用方法参数的顺序与它们作为键出现在实际函数中的顺序相同。即,当我调用 a_method("a", "b") 时,打印 "a,b" 的装饰器看起来如何?

最佳答案

看看inspect模块 - 这将为您检查各种代码对象属性。

>>> inspect.getfullargspec(a_method)
(['arg1', 'arg2'], None, None, None)

其他结果是 *args 和 **kwargs 变量的名称,以及提供的默认值。即。

>>> def foo(a, b, c=4, *arglist, **keywords): pass
>>> inspect.getfullargspec(foo)
(['a', 'b', 'c'], 'arglist', 'keywords', (4,))

请注意,某些可调用对象在某些 Python 实现中可能是不可自省(introspection)的。例如,在 CPython 中,C 中定义的一些内置函数不提供有关其参数的元数据。因此,如果您在内置函数上使用 inspect.getfullargspec(),您将得到一个 ValueError

从 Python 3.3 开始,您可以使用 inspect.signature()查看可调用对象的调用签名:

>>> inspect.signature(foo)
<Signature (a, b, c=4, *arglist, **keywords)>

https://stackoverflow.com/questions/218616/

相关文章:

linux - 递归查找具有特定扩展名的文件

python - Python 是强类型的吗?

python - 我应该在 Python 中使用 "camel case"还是下划线?

python - Python进程使用的总内存?

linux - 在shell中获取程序执行时间

linux - 在 Linux 系统上快速创建大文件

linux - chmod 777 到一个文件夹和所有内容

linux - 如果任何命令返回非零值,则中止 shell 脚本

python - Python 和 IPython 有什么区别?

python - 在 Python 中以 YYYY-MM-DD 获取今天的日期?