简体   繁体   English

分配与全局变量同名的局部变量时出错

[英]Error when assigning local variable with same name as a global variable

I am seeing an error when assigning either a global or an enclosing-function local to a local variable with the same name. 将全局或封闭函数局部分配给具有相同名称的局部变量时,我看到错误。 The code below illustrates this issue, where f() runs fine, while g() raises an error. 下面的代码说明了此问题,其中f()运行良好,而g()引发错误。 It seems like python knows that a is being assigned locally, so it says that all references to a are now local, even the references before a is actually assigned locally. 似乎python知道a是在本地分配的,因此它说对a所有引用现在都是本地的,即使a之前的引用实际上是在本地分配的。 What explains this behavior? 是什么解释了这种行为? I am running Python 2.7.12 :: Anaconda 4.2.0 (64-bit). 我正在运行Python 2.7.12 :: Anaconda 4.2.0(64位)。

In [18]: a = 1
    ...: 
    ...: def f():
    ...:   x = a
    ...:   print x
    ...: 
    ...: def g():
    ...:   a = a
    ...:   print a
    ...:   

In [19]: f()
1

In [20]: g()
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-20-d65ffd94a45c> in <module>()
----> 1 g()

<ipython-input-18-f3d970bdaa2b> in g()
      6 
      7 def g():
----> 8   a = a
      9   print a
     10 

UnboundLocalError: local variable 'a' referenced before assignment

The short answer is that, within g(), you need to declare 简短的答案是,在g()中,您需要声明

global a

if you want to be able to modify "a" from within a function and have this effect globally visible. 如果您希望能够在函数中修改“ a”并使此效果全局可见。 However, in your case, the effect of using "a" within g() is to convert this variable name to refer to a local-scope variable, which then hides the global "a" which you're attempting to use on the righthand side of your assignment, triggering the exception. 但是,在您的情况下,在g()中使用“ a”的作用是将该变量名称转换为引用局部作用域变量,然后隐藏了您试图在右侧使用的全局“ a”分配方面,触发异常。 This is more fully explained here . 在这里有更全面的解释。 There is also a Python FAQ which explains the rules that make f() work without the need for the "global a". 还有一个Python FAQ ,它解释了使f()起作用而无需使用“ global a”的规则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM