Python 列表函数参数名称 [英] Python list function argument names

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

问题描述

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

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

def foo(bar, buz):
    pass

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

推荐答案

使用 inspect 来自 Python 标准库的模块(最干净、最可靠的内省方式).

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

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

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

import inspect

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

完全满足您表达的要求.

completely meets your expressed requirements.

这篇关于Python 列表函数参数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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