在 python 中的赋值错误之前引用 [英] referenced before assignment error in python
问题描述
在 Python 中,我收到以下错误:
In Python I'm getting the following error:
UnboundLocalError: local variable 'total' referenced before assignment
在文件的开头(在出现错误的函数之前),我使用 global 关键字声明了 'total'.然后,在程序主体中,在调用使用 'total' 的函数之前,我将其赋值为 0.我尝试在各个地方(包括文件顶部,就在声明之后)将其设置为 0),但我无法让它工作.有没有人看到我做错了什么?
At the start of the file (before the function where the error comes from), I declare 'total' using the global keyword. Then, in the body of the program, before the function that uses 'total' is called, I assign it to 0. I've tried setting it to 0 in various places (including the top of the file, just after it is declared), but I can't get it to work. Does anyone see what I'm doing wrong?
推荐答案
我认为您错误地使用了全局".请参阅 Python 参考.你应该声明没有 global 的变量,然后在你想访问全局变量时在函数内部声明它global yourvar
.
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
看这个例子:
#!/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.
Because doA()
does not modify the global total the output is 1 not 11.
这篇关于在 python 中的赋值错误之前引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!