有没有一种简单的方法可以在python函数中获得参数名列表?
例如:
def func(a,b,c):
print magic_that_does_what_I_want()
>>> func()
['a','b','c']
谢谢
有没有一种简单的方法可以在python函数中获得参数名列表?
例如:
def func(a,b,c):
print magic_that_does_what_I_want()
>>> func()
['a','b','c']
谢谢
当前回答
如果你也想要这些值,你可以使用inspect模块
import inspect
def func(a, b, c):
frame = inspect.currentframe()
args, _, _, values = inspect.getargvalues(frame)
print 'function name "%s"' % inspect.getframeinfo(frame)[2]
for i in args:
print " %s = %s" % (i, values[i])
return [(i, values[i]) for i in args]
>>> func(1, 2, 3)
function name "func"
a = 1
b = 2
c = 3
[('a', 1), ('b', 2), ('c', 3)]
其他回答
如果你也想要这些值,你可以使用inspect模块
import inspect
def func(a, b, c):
frame = inspect.currentframe()
args, _, _, values = inspect.getargvalues(frame)
print 'function name "%s"' % inspect.getframeinfo(frame)[2]
for i in args:
print " %s = %s" % (i, values[i])
return [(i, values[i]) for i in args]
>>> func(1, 2, 3)
function name "func"
a = 1
b = 2
c = 3
[('a', 1), ('b', 2), ('c', 3)]
import inspect
def func(a,b,c=5):
pass
inspect.getargspec(func) # inspect.signature(func) in Python 3
(['a', 'b', 'c'], None, None, (5,))
Locals()返回一个包含本地名称的字典:
def func(a, b, c):
print(locals().keys())
打印参数列表。如果你使用其他局部变量,它们将包括在这个列表中。但是你可以在函数的开头复制。
这里不需要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__。