use*_*192 3 python function introspection
def thefunction(a=1,b=2,c=3):
pass
print allkeywordsof(thefunction) #allkeywordsof doesnt exist
Run Code Online (Sandbox Code Playgroud)
会给[a,b,c]
是否有像allkeywordsof这样的功能?
我不能改变里面的任何东西, thefunction
unu*_*tbu 19
我想你正在寻找inspect.getargspec:
import inspect
def thefunction(a=1,b=2,c=3):
pass
argspec = inspect.getargspec(thefunction)
print(argspec.args)
Run Code Online (Sandbox Code Playgroud)
产量
['a', 'b', 'c']
Run Code Online (Sandbox Code Playgroud)
如果你的函数包含位置和关键字参数,那么找到关键字参数的名称有点复杂,但不是太难:
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']
Run Code Online (Sandbox Code Playgroud)
你想要这样的东西吗:
>>> def func(x,y,z,a=1,b=2,c=3):
pass
>>> func.func_code.co_varnames[-len(func.func_defaults):]
('a', 'b', 'c')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3621 次 |
| 最近记录: |