在Python中,我遇到了以下错误:
UnboundLocalError: local variable 'total' referenced before assignment
在出错的函数之前的文件开头,我使用 global
关键字声明了 total
。然后,在程序主体中,在调用使用 total
的函数之前,我将它赋值为 0。我尝试过在各个地方(包括文件顶部和声明后紧接着)将其设置为 0,但是我无法让它正常工作。
有人看到我哪里做错了吗?
在Python中,我遇到了以下错误:
UnboundLocalError: local variable 'total' referenced before assignment
在出错的函数之前的文件开头,我使用 global
关键字声明了 total
。然后,在程序主体中,在调用使用 total
的函数之前,我将它赋值为 0。我尝试过在各个地方(包括文件顶部和声明后紧接着)将其设置为 0,但是我无法让它正常工作。
有人看到我哪里做错了吗?
我认为你在错误地使用 '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。
glob_val=None
,也就是说,我无法在没有值分配的情况下声明它)。 - amphibient我的情景
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 main()
self.x = 0
def increment():
self.x += 1
for i in range(5):
increment()
print(self.x)
def inside():
global var
var = 'info'
inside()
print(var)
>>>'info'
问题已解决
global
的用法。 - General Grievance