且构网

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

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

更新时间:2023-02-26 19:51:23

您可以使用当地人()来获取局部变量的字典在你的功能,这样

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}

这是一个有点hackish,但是,由于当地人()返回在局部范围内的所有变量,不​​仅传递给函数的参数,所以如果你不ŧ调用它在结果可能包含更多的信息功能的最顶端比你想要​​的:

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}

我宁愿构建,您需要使用函数的顶部,在其他的答案提出的变量的字典或列表。这更加明确并传达你的code的意图更明确的方式,恕我直言。

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.