在 Python 中,我收到以下错误:
UnboundLocalError: local variable 'total' referenced before assignment
在文件的开头(在错误来自的函数之前),我total
使用global
关键字声明。然后,在程序主体中,在调用使用的函数之前total
,我将其分配为 0。我尝试在不同的地方将其设置为 0(包括文件的顶部,就在它被声明之后),但是我无法让它工作。
有谁看到我做错了什么?
在 Python 中,我收到以下错误:
UnboundLocalError: local variable 'total' referenced before assignment
在文件的开头(在错误来自的函数之前),我total
使用global
关键字声明。然后,在程序主体中,在调用使用的函数之前total
,我将其分配为 0。我尝试在不同的地方将其设置为 0(包括文件的顶部,就在它被声明之后),但是我无法让它工作。
有谁看到我做错了什么?
我认为您错误地使用了“全局”。请参阅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()
不修改全局总数,所以输出是 1 而不是 11。
我的情景
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'
问题结束
我想提一下,你可以对函数范围这样做
def main()
self.x = 0
def increment():
self.x += 1
for i in range(5):
increment()
print(self.x)