为什么在函数中给全局变量赋值时会出现“引用前赋值”错误?

105 投票
4 回答
284947 浏览
提问于 2025-04-15 11:33

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

UnboundLocalError: local variable 'total' referenced before assignment

在文件的开头(出错的函数之前),我用global关键字声明了total。然后,在程序的主体部分,在调用使用total的函数之前,我把它赋值为0。我尝试在不同的地方把它设置为0(包括在文件顶部,刚声明之后),但就是无法让它正常工作。

有没有人能帮我看看我哪里做错了?

4 个回答

1

我想提一下,你可以这样做来处理函数的作用域。

def main()

  self.x = 0

  def increment():
    self.x += 1
  
  for i in range(5):
     increment()
  
  print(self.x)
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()
203

我觉得你对'global'的用法有点不对。你可以查看一下Python的官方文档。你应该在函数外面声明变量,而在函数内部如果想要使用全局变量时,就需要用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。

撰写回答