问题描述
为什么下面不是在函数内部工作而是在外部工作?
def foo():共同 = {'abc':'xyz'}打印(当地人())当地人().更新(普通)打印(当地人(),ABC)富()
错误:NameError:未定义全局名称abc"
如果我在函数外运行它,它就可以工作
common = {'abc' : 'xyz'}打印(当地人())当地人().更新(普通)打印(当地人(),ABC)
根据 本地人文档:
注意本词典内容不可修改;更改可能不会影响解释器使用的局部变量和自由变量的值.
所以它不起作用,因为它不打算工作.但是现在要回答您的问题,它在全局范围内有效,因为可以修改 globals
,全局文档 没有说明不应修改此 [...]".
而且,很明显,当您处于全局范围内时, global 是 locals:
>>>globals() 是 locals()真的所以您正在修改全局变量,这是允许的.
Why below is not working inside function but working outside?
def foo():
common = {'abc' : 'xyz'}
print(locals())
locals().update(common)
print(locals(),abc)
foo()
Error : NameError: global name 'abc' is not defined
If i run it outside function, it works
common = {'abc' : 'xyz'}
print(locals())
locals().update(common)
print(locals(),abc)
According to the locals documentation:
So it's not working because it's not intended to work. But to answer your question now, it works in the global scope because modifying the globals
is possible, the globals documentation don't have the note telling "this [...] should not be modified".
And, obviously, when you're in the global scope, global is locals:
>>> globals() is locals()
True
So you're modifying globals, which is permitted.
这篇关于Python 本地更新不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!