[英]Why there is no error without using global keyword
In this file I am using a dictionary named modelDict
declared globally and I am using it in multiple functions ( addCharToModelDict, dumpModelDict
). 在此文件中,我使用的是全局声明的名为modelDict
的字典,并且在多个函数( addCharToModelDict, dumpModelDict
)中使用它。 I haven't used global
keyword inside these functions to use the global modelDict
. 我没有在这些函数中使用global
关键字来使用global modelDict
。
addCharToModelDict
is updating it and dumpModelDict
is writing it back to file in the end. addCharToModelDict
正在更新它,而dumpModelDict
将其写回到文件中。
Everything works fine!! 一切正常!
Why this is happening?? 为什么会这样? Isn't using global keyword is necessary?? 是不是使用全局关键字是必要的?
The global
keyword is only required when rebinding the name. 仅在重新绑定名称时才需要global
关键字。 Your operations mutate the object instead. 您的操作将突变该对象。
You are working with modelDict
variable from globals
(python trying to find modelDict
in locals but can't then It tries to find it in globals
and succeeded). 您正在使用来自globals
modelDict
变量(python试图在本地globals
中查找modelDict
,但随后无法在globals
找到它并成功)。 This works If You use variable defined in outer code either read or update. 如果您使用外部代码中定义的变量进行读取或更新,则此方法有效。
d = {}
def foo():
a = d.get('x')
d[4] = True
foo()
If You will try to reassign new data to variable with this name (rebind it) You will get Error. 如果您尝试使用该名称将新数据重新分配给变量(重新绑定),则会收到错误消息。
>>> d = {}
>>> def foo():
a = d.get('x')
d = {4: True}
>>> foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in foo
UnboundLocalError: local variable 'd' referenced before assignment
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.