如何获取方法参数名称?
鉴于函数 a_method
的定义类似于
def a_method(arg1, arg2):
pass
从 a_method
本身开始,我如何获取参数名称 - 例如,作为字符串元组,如 ( “arg1”,“arg2”)?
Given that a function a_method
has been defined like
def a_method(arg1, arg2):
pass
Starting from a_method
itself, how can I get the argument names - for example, as a tuple of strings, like ("arg1", "arg2")
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(19)
返回参数名称列表,处理部分函数和常规函数:
Returns a list of argument names, takes care of partials and regular functions:
更新 Brian 的回答:
如果 Python 3 中的函数有仅关键字参数,那么您需要使用inspect.getfullargspec:
产生以下结果:
Update for Brian's answer:
If a function in Python 3 has keyword-only arguments, then you need to use
inspect.getfullargspec
:yields this:
在 python 3 中,下面是将
*args
和**kwargs
制作成dict
(对于 python 使用OrderedDict
<3.6 维护dict
命令):In python 3, below is to make
*args
and**kwargs
into adict
(useOrderedDict
for python < 3.6 to maintaindict
orders):操作某些函数的参数名称的最简单方法:
结果:
由于您获得了特定的参数名称,因此这种方法会更容易:
结果:
Easiest way to manipulate parameters names of some function:
Result:
Making this way will be even easier since you get the specific one:
Result:
对于像我一样正在寻找一种解决方案的人,我还有另一个建议,该解决方案将装饰器中的所有参数及其值(默认或非默认)放入字典中。
现在在像这样的装饰器中打印 get_arguments 的返回值
并将其应用到类似的函数上
将为我们提供
相同的方法
这当然不是最漂亮的解决方案,但这是我见过的第一个解决方案这正是我想要的。
I have another suggestion for those who, like me, are looking for a solution that puts inside a decorator all parameters and their values (default or not) into a dictonary.
Now printing the return value of get_arguments inside a decorator like this one
and apply it on a function like
will give us
Same works for methods
It's certainly not the prettiest solution, but it's the first one I've seen that does exactly what I want.
从 python 3.0 开始,简单易读的答案:
Simple easy to read answer as of python 3.0 onwards:
要更新一点 Brian 的答案,现在有一个很好的
inspect.signature
向后移植,您可以在较旧的 python 版本中使用:funcsigs
。所以我个人的偏好是为了
好玩,如果你有兴趣使用
Signature
对象,甚至动态创建具有随机签名的函数,你可以看看我的makefun
项目。To update a little bit Brian's answer, there is now a nice backport of
inspect.signature
that you can use in older python versions:funcsigs
.So my personal preference would go for
For fun, if you're interested in playing with
Signature
objects and even creating functions with random signatures dynamically you can have a look at mymakefun
project.我在谷歌上搜索如何打印函数名称并为作业提供参数,我必须创建一个装饰器来打印它们,我使用了这个:
I was googling to find how to print function name and supplied arguments for an assignment I had to create a decorator to print them and I used this:
现在
dir()
和vars()
怎么样?似乎完全按照要求做的超级简单......
必须从函数范围内调用。
但要小心它会返回所有局部变量,所以一定要在如果需要的话,可以在函数的最开始处。
另请注意,正如评论中所指出的,这不允许从范围之外完成。 所以不完全是OP的场景,但仍然符合问题标题。 因此我的回答是这样的。
What about
dir()
andvars()
now?Seems doing exactly what is being asked super simply…
Must be called from within the function scope.
But be wary that it will return all local variables so be sure to do it at the very beginning of the function if needed.
Also note that, as pointed out in the comments, this doesn't allow it to be done from outside the scope. So not exactly OP's scenario but still matches the question title. Hence my answer.
看一下
inspect
模块 - 这将执行以下操作为您检查各种代码对象属性。其他结果是 *args 和 **kwargs 变量的名称以及提供的默认值。 IE。
请注意,某些可调用对象在 Python 的某些实现中可能无法自省。 例如,在 CPython 中,C 中定义的一些内置函数不提供有关其参数的元数据。 因此,如果您在内置函数上使用
inspect.getfullargspec()
,您将收到ValueError
。从 Python 3.3 开始,您可以使用
inspect .signature()
查看可调用对象的调用签名:Take a look at the
inspect
module - this will do the inspection of the various code object properties for you.The other results are the name of the *args and **kwargs variables, and the defaults provided. ie.
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 useinspect.getfullargspec()
on a built-in function.Since Python 3.3, you can use
inspect.signature()
to see the call signature of a callable object:在 CPython 中,参数的数量为
且它们的名称位于这些是 CPython 的实现细节的开头
,因此这可能不适用于其他 Python 实现,例如 IronPython 和 Jython。
允许“传递”参数的一种可移植方法是使用签名
func(*args, **kwargs)
定义函数。 这在例如 matplotlib 中被大量使用,其中外部 API 层将大量关键字参数传递给较低级别的 API。In CPython, the number of arguments is
and their names are in the beginning of
These are implementation details of CPython, so this probably does not work in other implementations of Python, such as IronPython and Jython.
One portable way to admit "pass-through" arguments is to define your function with the signature
func(*args, **kwargs)
. This is used a lot in e.g. matplotlib, where the outer API layer passes lots of keyword arguments to the lower-level API.Python 3 版本是:
该方法返回一个包含 args 和 kwargs 的字典。
The Python 3 version is:
The method returns a dictionary containing both args and kwargs.
在装饰器方法中,您可以通过以下方式列出原始方法的参数:
如果
**kwargs
对您很重要,那么它会有点复杂:示例:
In a decorator method, you can list arguments of the original method in this way:
If the
**kwargs
are important for you, then it will be a bit complicated:Example:
Python 3.5+:
所以以前:
现在:
测试:
假设我们有函数'function',它接受参数'arg',这将评估为 True,否则评估为 False。
来自 Python 控制台的示例:
Python 3.5+:
So previously:
Now:
To test:
Given that we have function 'function' which takes argument 'arg', this will evaluate as True, otherwise as False.
Example from the Python console:
我认为您正在寻找的是当地人的方法 -
I think what you're looking for is the locals method -
我认为使用装饰器可以满足您的需求。
运行它,它将产生以下输出:
Here is something I think will work for what you want, using a decorator.
Run it, it will yield the following output:
在具有
Signature
对象的 Python 3.+ 中,获取参数名称到值之间的映射的一种简单方法是使用 Signature 的bind()
方法!例如,这是一个用于打印这样的地图的装饰器:
In Python 3.+ with the
Signature
object at hand, an easy way to get a mapping between argument names to values, is using the Signature'sbind()
method!For example, here is a decorator for printing a map like that:
这是另一种无需使用任何模块即可获取函数参数的方法。
输出:
Here is another way to get the function parameters without using any module.
Output:
inspect.signature
非常慢。 最快的方法是inspect.signature
is very slow. Fastest way is