R S*_*R S 241 python parameters
可能重复:
在python中获取方法参数名称
有没有一种简单的方法可以在python函数中获取参数名称列表?
例如:
def func(a,b,c):
print magic_that_does_what_I_want()
>>> func()
['a','b','c']
Run Code Online (Sandbox Code Playgroud)
谢谢
sim*_*rsh 282
那么我们实际上并不需要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,)
Run Code Online (Sandbox Code Playgroud)
对于Python 2.5及以上,使用func_code替代__code__和func_defaults取代__defaults__.
小智 191
locals()(Python 2的文档,Python 3)返回一个具有本地名称的字典:
def func(a,b,c):
print(locals().keys())
Run Code Online (Sandbox Code Playgroud)
打印参数列表.如果您使用其他局部变量,那么这些变量将包含在此列表中.但是你可以在函数的开头复制一份.
kmk*_*lan 167
如果您还想要这些值,则可以使用该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)]
Run Code Online (Sandbox Code Playgroud)
Oli*_*Oli 97
import inspect
def func(a,b,c=5):
pass
inspect.getargspec(func) # inspect.signature(func) in Python 3
(['a', 'b', 'c'], None, None, (5,))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
244392 次 |
| 最近记录: |