1

有人可以解释一下这段小代码是如何工作的吗?

info = {}
info.update(locals())
info.pop('self', None)
info.pop('info', None)

我假设,如果我错了,请纠正我,但它会获取当前函数中的所有变量并将它们放入 dict 并删除 self 和它放入的 dict,对吗?除了 self 和我可能不想进入的 dict 之外,还有什么?

仅 JSON 序列化该字典并发布它会有什么问题吗?

4

2 回答 2

3

This probably comes from the Django template and the locals trick. The idea is to populate a number of variables inside a function, and use locals() to pass them on to a template. It saves the effort of creating a new dictionary with all those variables.

Specifically, your code creates a dictionary of all the local variables and removes self (the class object parameter) and info (the variable that was just created). All other local variables are returned.

You could then JSON serialize the data, as long as the data can be serialized. DateTime variables must be converted to a string first, for example.

于 2015-09-09T23:13:17.820 回答
0

该代码创建了一个名为“info”的新字典,并将所有本地 python 变量分配给它。注意:这些是指向本地环境中相同对象的指针,因此如果您修改其中的列表或字典,info它也会在您的环境中更改(这可能是也可能不是所需的行为)。

locals() 更新并返回表示当前本地符号表的字典。自由变量在函数块中调用时由 locals() 返回,而不是在类块中。

注意 不得修改本词典的内容;更改可能不会影响解释器使用的局部变量和自由变量的值。

info.pop('self', None)并将info.pop('info', None)分别从您的新info字典中删除“self”和“info”。如果他们不存在,他们会返回None。请注意,info.pop('self')如果 'self' 不在字典中,则会返回 KeyError。

于 2015-09-09T23:20:23.317 回答