1

In this file I am using a dictionary named modelDict declared globally and I am using it in multiple functions (addCharToModelDict, dumpModelDict). I haven't used global keyword inside these functions to use the global modelDict.
addCharToModelDict is updating it and dumpModelDict is writing it back to file in the end.

Everything works fine!!

Why this is happening?? Isn't using global keyword is necessary??

4

2 回答 2

7

仅在重新绑定global名称时才需要关键字。您的操作会改变对象。

于 2013-06-26T13:26:04.220 回答
2

您正在使用modelDict变量 from globals(python 试图modelDict在本地查找但不能然后它试图找到它globals并成功)。如果您使用外部代码中定义的变量读取或更新,则此方法有效。

d = {}
def foo():
    a = d.get('x')
    d[4] = True
foo()

如果您尝试将新数据重新分配给具有此名称的变量(重新绑定它),您将收到错误。

>>> 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
于 2013-06-26T13:41:45.153 回答