Python 列表函数参数名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3517892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:31:04  来源:igfitidea点击:

Python list function argument names

pythonfunctionarguments

提问by Bemmu

Is there a way to get the parameter names a function takes?

有没有办法获取函数采用的参数名称?

def foo(bar, buz):
    pass

magical_way(foo) == ["bar", "buz"]

采纳答案by Alex Martelli

Use the inspectmodule from Python's standard library (the cleanest, most solid way to perform introspection).

使用Python 标准库中的检查模块(最干净、最可靠的内省方式)。

Specifically, inspect.getargspec(f)returns the names and default valuesof f's arguments -- if you only want the names and don't care about special forms *a, **k,

具体来说,inspect.getargspec(f)返回名称和默认值f的参数-如果你只是想名字和不关心特殊形式*a**k

import inspect

def magical_way(f):
    return inspect.getargspec(f)[0]

completely meets your expressed requirements.

完全满足您表达的要求。

回答by John La Rooy

>>> import inspect
>>> def foo(bar, buz):
...     pass
... 
>>> inspect.getargspec(foo)
ArgSpec(args=['bar', 'buz'], varargs=None, keywords=None, defaults=None)
>>> def magical_way(func):
...     return inspect.getargspec(func).args
... 
>>> magical_way(foo)
['bar', 'buz']