小编典典

在python函数中获取参数名称的列表

python

有没有一种简单的方法可以进入python函数并获取参数名称列表?

例如:

def func(a,b,c):
    print magic_that_does_what_I_want()

>>> func()
['a','b','c']

谢谢


阅读 1324

收藏
2020-02-23

共1个答案

小编典典

好吧,我们实际上不需要inspect这里。

>>> func = lambda x, y: (x, y)
>>> 
>>> func.__code__.co_argcount
2
>>> func.__code__.co_varnames
('x', 'y')
>>>
>>> def func2(x,y=3):
...  print(func2.__code__.co_varnames)
...  pass # Other things
... 
>>> func2(3,3)
('x', 'y')
>>> 
>>> func2.__defaults__
(3,)

对于Python 2.5及更高版本,请使用func_code代替__code__func_defaults代替__defaults__

2020-02-23