且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取传递给函数的参数的列表/元组/字典?

更新时间:2023-11-11 17:34:46

您可以使用 locals() 来获取函数中局部变量的字典,如下所示:

You can use locals() to get a dict of the local variables in your function, like this:

def foo(a, b, c):
    print locals()

>>> foo(1, 2, 3)
{'a': 1, 'c': 3, 'b': 2}

然而,这有点骇人听闻,因为 locals() 返回本地范围内的所有变量,而不仅仅是传递给函数的参数,因此如果您不立即调用它函数的顶部结果可能包含比您想要的更多的信息:

This is a bit hackish, however, as locals() returns all variables in the local scope, not only the arguments passed to the function, so if you don't call it at the very top of the function the result might contain more information than you want:

def foo(a, b, c):
    x = 4
    y = 5
    print locals()

>>> foo(1, 2, 3)
{'y': 5, 'x': 4, 'c': 3, 'b': 2, 'a': 1}

我宁愿按照其他答案中的建议,在函数顶部构建一个字典或您需要的变量列表.恕我直言,它更明确,并以更清晰的方式传达您的代码意图.

I would rather construct a dict or list of the variables you need at the top of your function, as suggested in the other answers. It's more explicit and communicates the intent of your code in a more clear way, IMHO.