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

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

UnboundLocalError: local variable 'total' referenced before assignment

在文件的开始部分(在错误出现的函数之前) ,我使用 global关键字声明 total。然后,在程序体中,在调用使用 total的函数之前,我将它赋值为0。我已经尝试在不同的位置(包括文件的顶部,在它被声明之后)将它设置为0,但是我不能让它工作。

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

257420 次浏览

I think you are using 'global' incorrectly. See Python reference. You should declare variable without global and then inside the function when you want to access global variable you declare it global yourvar.

#!/usr/bin/python


total


def checkTotal():
global total
total = 0

See this example:

#!/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()

Because doA() does not modify the global total the output is 1 not 11.

My Scenario

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()
def inside():
global var
var = 'info'
inside()
print(var)


>>>'info'

problem ended

I want to mention that you can do like this for the function scope

def main()


self.x = 0


def increment():
self.x += 1
  

for i in range(5):
increment()
  

print(self.x)