1

この小さなコードがどのように機能するかを誰か説明してもらえますか?

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

私が間違っている場合は修正してください。ただし、現在の関数のすべての変数を取得し、それらを辞書に入れ、自己とそれが入れられた辞書を削除します。正しいですか? 自己と、そこに入りたくないかもしれないディクテーション以外に何かありますか?

その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)からそれぞれ「self」と「info」を削除します。info存在しない場合は、 を返しNoneます。info.pop('self')「self」が辞書にない場合、 KeyError が返されることに注意してください。

于 2015-09-09T23:20:23.317 に答える