如何获取方法参数名称? [英] How to get method parameter names?

查看:99
本文介绍了如何获取方法参数名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出Python函数:

Given the Python function:

def a_method(arg1, arg2):
    pass

如何提取参数的数量和名称。即,考虑到我对 func 的引用,我希望 func。[something] 返回( arg1, arg2)

How can I extract the number and names of the arguments. I.e., given that I have a reference to func, I want the func.[something] to return ("arg1", "arg2").

使用情况是我有一个装饰器,我希望以与实际函数中的键相同的顺序使用方法参数。即,当我调用 a_method( a, b) a,b $ c>?

The usage scenario for this is that I have a decorator, and I wish to use the method arguments in the same order that they appear for the actual function as a key. I.e., how would the decorator look that printed "a,b" when I call a_method("a", "b")?

推荐答案

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

Take a look at the inspect module - this will do the inspection of the various code object properties for you.

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

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

The other results are the name of the *args and **kwargs variables, and the defaults provided. ie.

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

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

Note that some callables may not be introspectable in certain implementations of Python. For Example, in CPython, some built-in functions defined in C provide no metadata about their arguments. As a result, you will get a ValueError if you use inspect.getfullargspec() on a built-in function.

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

Since Python 3.3, you can use inspect.signature() to see the call signature of a callable object:

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

这篇关于如何获取方法参数名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆