在python中赋值错误之前引用

Jer*_*emy 62 python

在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.

  • 如果您在本地范围内分配全局变量,那么您只需要"global"关键字就没有任何价值.因此,在您的示例中,checkTotal()中不需要全局声明. (26认同)
  • 我的意思是值得注意*当然!没有删除读取仍然无法编辑注释.:( (3认同)

zin*_*ing 6

我的场景

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)