在Python中我收到以下错误:
UnboundLocalError: local variable 'total' referenced before assignment
Run Code Online (Sandbox Code Playgroud)
在文件的开头(在出现错误的函数之前),我使用global关键字声明'total'.然后,在程序的主体中,在调用使用'total'的函数之前,我将它指定为0.我已经尝试在各个地方将它设置为0(包括文件的顶部,就在它被声明之后) ),但我不能让它工作.有谁看到我做错了什么?
ste*_*anB 131
我认为你错误地使用'全球'.请参阅Python参考.你应该在没有全局的情况下声明变量,然后在你想要访问全局变量时在函数内部声明它global yourvar.
#!/usr/bin/python
total
def checkTotal():
global total
total = 0
Run Code Online (Sandbox Code Playgroud)
看这个例子:
#!/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()
Run Code Online (Sandbox Code Playgroud)
因为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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
146906 次 |
| 最近记录: |