分配与全局变量同名的局部变量时出错 [英] Error when assigning local variable with same name as a global variable

查看:74
本文介绍了分配与全局变量同名的局部变量时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在将全局或封闭函数局部分配给同名的局部变量时,我看到错误.下面的代码说明了这个问题,其中 f() 运行良好,而 g() 引发错误.似乎python知道a是在本地分配的,所以它说所有对a的引用现在都是本地的,即使是a之前的引用实际上是在本地分配的.什么解释了这种行为?我正在运行 Python 2.7.12 :: Anaconda 4.2.0(64 位).

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. 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. What explains this behavior? I am running Python 2.7.12 :: Anaconda 4.2.0 (64-bit).

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

推荐答案

简短的回答是,在 g() 中,你需要声明

The short answer is that, within g(), you need to declare

global a

如果您希望能够在函数内修改a"并使此效果全局可见.但是,在您的情况下,在 g() 中使用a"的效果是将此变量名称转换为引用局部范围变量,然后隐藏您尝试在右侧使用的全局a"任务的一部分,触发异常.这有更充分的解释 此处.还有一个 Python FAQ 解释了使 f() 在不需要全局 a"的情况下工作的规则.

if you want to be able to modify "a" from within a function and have this effect globally visible. 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. 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".

这篇关于分配与全局变量同名的局部变量时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆