当在函数中给全局变量赋值时,为什么会出现“referenced before assignment”错误?

104

在Python中,我遇到了以下错误:

UnboundLocalError: local variable 'total' referenced before assignment

在出错的函数之前的文件开头,我使用 global 关键字声明了 total。然后,在程序主体中,在调用使用 total 的函数之前,我将它赋值为 0。我尝试过在各个地方(包括文件顶部和声明后紧接着)将其设置为 0,但是我无法让它正常工作。

有人看到我哪里做错了吗?


5
你在函数中声明了全局变量吗? - Nikhil
2
这个回答解决了你的问题吗?在第一次使用后重新分配本地变量时出现UnboundLocalError - Tomerikoo
4个回答

202

我认为你在错误地使用 'global'。请参见Python参考。你应该在不使用 global 的情况下声明变量,然后在函数内部当你要访问全局变量时,你需要声明 global yourvar

#!/usr/bin/python

total

def checkTotal():
    global total
    total = 0

看这个例子:

#!/usr/bin/env python

total = 0

def doA():
    # not accessing global total
    total = 10

def doB():
    global total
    total = total + 1

def checkTotal():
    # global total - not required as global is required
    # only for assignment - thanks for comment Greg
    print total

def main():
    doA()
    doB()
    checkTotal()

if __name__ == '__main__':
    main()

因为doA()没有修改全局变量total,所以输出结果是1而不是11。


38
需要注意的是,只有在本地作用域中对全局变量进行赋值时才需要使用“global”关键字。因此,在您的示例中,在checkTotal()函数中不需要使用global声明。 - Greg Hewgill
1
全面的回答,以及对问题背后本质误解的深入分析。 - Jarret Hardie
3
我想说的是当然可能值得注意!但仍无法在不删除和重新添加的情况下编辑评论。 :( - Greg Hewgill
在声明全局变量时,我必须为其分配一个值(我使用了glob_val=None,也就是说,我无法在没有值分配的情况下声明它)。 - amphibient

7

我的情景

def example():
    cl = [0, 1]
    def inner():
        #cl = [1, 2] # access this way will throw `reference before assignment`
        cl[0] = 1 
        cl[1] = 2   # these won't

    inner()

1
我想提一下,你可以这样做函数作用域。
def main()

  self.x = 0

  def increment():
    self.x += 1
  
  for i in range(5):
     increment()
  
  print(self.x)

-2
def inside():
   global var
   var = 'info'
inside()
print(var)

>>>'info'

问题已解决


2
通过简单的解释或注释来说明您的代码如何工作将会很有帮助。 - Anurag A S
被接受的答案似乎已经涵盖了global的用法。 - General Grievance
这只是重复了被接受的答案所说的内容,但正如Anurag AS所提到的那样,没有解释。而且正如General Grievance所说的,如果被接受的答案已经涵盖了全局变量的使用,那么为什么要发布一个未经解释的代码片段,对谈话毫无贡献呢? - Mike S

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接