我遇到了 Python 中内置函数 locals() 的奇怪行为。具体不好解释,请看一段代码:
def Main():
def F(l=locals()): print 'F', id(l), l
a= 100
F()
print '1', id(locals()), locals()
F()
在局部函数 F
中,我将 locals()
分配给 l
作为 enclosure 的默认值。由于 locals()
是一个 dict
,它的引用被复制到 l
。所以最后三行应该有相同的结果。
然而结果是这样的:
F 139885919456064 {}
1 139885919456064 {'a': 100, 'F': <function F at 0x7f39ba8969b0>}
F 139885919456064 {'a': 100, 'F': <function F at 0x7f39ba8969b0>}
三个print
语句几乎同时被调用,locals()
和l
的id
> 相同,但是F
中使用的第一个l
没有内容。
我不明白为什么会这样。谁能解释这种现象?或者这是一个已知/未知的错误?
非常感谢!
最佳答案
如果您阅读 docs对于 locals
函数,您会看到
Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks.
locals()
不只是返回局部变量的字典;它还更新字典以反射(reflect)当前局部变量值。
关于Python:locals() 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44075902/