简体   繁体   English

为什么不使用全局关键字就没有错误

[英]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.

相关问题 有没有办法在不使用全局关键字或循环的情况下做到这一点? - is there a way of doing this without using global keyword or loops? 在不使用全局关键字的情况下更改函数中的全局变量 - Changing a global variable in a function without using global keyword 如何使用 tkinter 中的按钮更改没有全局关键字的全局变量? - How to change a global variable without global keyword using a button in tkinter? 是否有使用 global 关键字的替代方法? - Is there an alternative to using the global keyword? 在没有全局关键字的情况下使变量完全全局化 - Make Variable entirely global without global keyword 为什么非本地关键字被全局关键字“中断”? - Why is nonlocal keyword being 'interrupted' by a global keyword? 为什么在这种情况下不需要全局关键字? - Why is the global keyword not required in this case? 为什么对象不需要全局关键字 - why is the global keyword not needed with an object 尝试使用a函数中的global关键字修改Global变量时出错 - Error while Trying to modify Global variable using global keyword from the a function 下面的代码在保存 Function 中有全局关键字,没有这个字程序将无法运行,有人可以解释为什么吗? - Below Code has Global Keyword in Save Function , without This Word Program will Not Work, Can Someone explain Why?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM