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

发布于 2021-02-02 23:10:16

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

例如:

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

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

谢谢

关注者
0
被浏览
95
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    好吧,我们实际上不需要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__



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看