获取函数Python的关键字参数

2024-10-01 11:41:51 发布

您现在位置:Python中文网/ 问答频道 /正文

def thefunction(a=1,b=2,c=3):
    pass

print allkeywordsof(thefunction) #allkeywordsof doesnt exist

会得到[a,b,c]

有没有像allkeywordsof这样的函数?在

我不能改变里面的任何东西,thefunction


Tags: 函数defpassexistprintdoesntthefunctionallkeywordsof
3条回答

我想你在找inspect.getargspec

import inspect

def thefunction(a=1,b=2,c=3):
    pass

argspec = inspect.getargspec(thefunction)
print(argspec.args)

收益率

^{pr2}$

如果函数同时包含位置参数和关键字参数,则查找关键字参数的名称会比较复杂,但不会太难:

def thefunction(pos1, pos2, a=1,b=2,c=3, *args, **kwargs):
    pass

argspec = inspect.getargspec(thefunction)

print(argspec)
# ArgSpec(args=['pos1', 'pos2', 'a', 'b', 'c'], varargs='args', keywords='kwargs', defaults=(1, 2, 3))

print(argspec.args)
# ['pos1', 'pos2', 'a', 'b', 'c']

print(argspec.args[-len(argspec.defaults):])
# ['a', 'b', 'c']

你想要这样的东西吗:

>>> def func(x,y,z,a=1,b=2,c=3):
    pass

>>> func.func_code.co_varnames[-len(func.func_defaults):]
('a', 'b', 'c')

您可以执行以下操作以获得您所要查找的内容。在

>>> 
>>> def funct(a=1,b=2,c=3):
...     pass
... 
>>> import inspect
>>> inspect.getargspec(funct)[0]
['a', 'b', 'c']
>>> 

相关问题 更多 >