def thefunction(a=1,b=2,c=3):
pass
print allkeywordsof(thefunction) #allkeywordsof doesnt exist
这将给出[a,b,c]。
是否有类似于allkeywordsof的函数?
我无法更改thefunction
内部的任何内容。
def thefunction(a=1,b=2,c=3):
pass
print allkeywordsof(thefunction) #allkeywordsof doesnt exist
这将给出[a,b,c]。
是否有类似于allkeywordsof的函数?
我无法更改thefunction
内部的任何内容。
我认为你正在寻找 inspect.getargspec:
import inspect
def thefunction(a=1,b=2,c=3):
pass
argspec = inspect.getargspec(thefunction)
print(argspec.args)
产生,得出(指程序输出结果)['a', 'b', 'c']
如果你的函数既包含位置参数又包含关键字参数,那么找到关键字参数的名称会稍微复杂一些,但并不太难: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']
inspect.getargspec(thefunction).args
- jamylakargspec.args[-len(argspec.defaults):]
应该被接受,因为它回答了这个问题。 - jamylakgetargspec
自v3版本起已被弃用(https://docs.python.org/3/library/inspect.html#inspect.getargspec),请改用`getfullargspec`。 - nocibambi>>> def func(x,y,z,a=1,b=2,c=3):
pass
>>> func.func_code.co_varnames[-len(func.func_defaults):]
('a', 'b', 'c')
inspect.getargspec()
也会返回非关键字参数。 - Ashwini Chaudharyinspect
,现在肯定会学习它了。 :) - Ashwini Chaudharyfunc_code
已被重命名为__code__
。 - naught101func.__code__.co_varnames
也会返回本地变量。 - nocibambi为了准确地获得您想要的内容,您可以采取以下措施。
>>>
>>> def funct(a=1,b=2,c=3):
... pass
...
>>> import inspect
>>> inspect.getargspec(funct)[0]
['a', 'b', 'c']
>>>