我目前正在研究变量范围以及如何修改/复制它们,因为我想在 IPython 中动态地对一些结果进行后处理。 关于 locals()、vars() 和 globals() 的困惑现在对我来说是真实存在的。 特别是因为这段代码的输出:
Python 3.6.1 (v3.6.1:69c0db5050, Mar 21 2017, 01:21:04)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> locals()["test"] = 5
>>> print(test)
5
根据不仅仅是简短的文档,这在我看来是不可能的:
Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored.
(出于 vars() 函数的 description 中所述的任何原因)
我希望有人能启发我:)
最佳答案
在模块范围内,locals()
返回可以修改的全局模块字典。函数中的局部变量是不同的。这里,变量没有改变。正如其他地方提到的,这完全取决于实现。你不能依赖 locals()
作为一名作家。
>>> def foo():
... x = 2
... locals()['x'] = 3
... print(x)
...
>>>
>>> foo()
2
编辑
在 cpython
中,局部变量被转换为框架对象上的槽。当 python 运行程序时,“x”不再是“x”,它是槽中的索引。
>>> from dis import dis
>>> dis(foo)
2 0 LOAD_CONST 1 (2)
2 STORE_FAST 0 (x)
3 4 LOAD_CONST 2 (3)
6 LOAD_GLOBAL 0 (locals)
8 CALL_FUNCTION 0
10 LOAD_CONST 3 ('x')
12 STORE_SUBSCR
4 14 LOAD_GLOBAL 1 (print)
16 LOAD_FAST 0 (x)
18 CALL_FUNCTION 1
20 POP_TOP
22 LOAD_CONST 0 (None)
24 RETURN_VALUE
STORE_FAST 0
表示将当前值(恰好为 2)存入 slot 0。
关于python - 写入 locals() 的工作方式与说明它不是的文档相反,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44357111/