【问题标题】:Why do I get a "referenced before assignment" error when assigning to a global variable in a function?为什么在分配给函数中的全局变量时会出现“分配前引用”错误?
【发布时间】:2010-10-25 17:23:42
【问题描述】:

在 Python 中,我收到以下错误:

UnboundLocalError: local variable 'total' referenced before assignment

在文件的开头(在错误来自的函数之前),我使用global 关键字声明total。然后,在程序的主体中,在调用使用total 的函数之前,我将其分配为0。我尝试在不同的地方将其设置为0(包括文件的顶部,就在它被声明之后),但我无法让它工作。

有人看到我做错了吗?

【问题讨论】:

标签: python global-variables


【解决方案1】:

我认为您错误地使用了“全局”。见Python reference。您应该声明不带全局变量的变量,然后在要访问全局变量时在函数内部声明它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。

【讨论】:

  • 如果您在局部范围内分配给全局变量,则只需要“global”关键字可能一文不值。因此,在您的示例中,checkTotal() 中不需要全局声明。
  • 全面的答案,并对问题背后的基本误解进行了充分的分析。
  • 我的意思是它当然值得注意!仍然无法在没有删除读取的情况下编辑 cmets。 :(
  • 在声明一个全局变量时,我必须给它赋值(我做了glob_val=None,IOW,没有赋值我无法声明它
【解决方案2】:

我的场景

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()

【讨论】:

    【解决方案3】:
    def inside():
       global var
       var = 'info'
    inside()
    print(var)
    
    >>>'info'
    

    问题结束

    【讨论】:

    • 通过简单的解释或评论来解释你的代码是如何工作的会很有帮助
    • 接受的答案似乎已经涵盖了global 的用法。
    【解决方案4】:

    我想提一下,你可以对函数范围这样做

    def main()
    
      self.x = 0
    
      def increment():
        self.x += 1
      
      for i in range(5):
         increment()
      
      print(self.x)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-03
      • 2012-04-26
      • 2018-07-16
      • 2020-07-06
      相关资源
      最近更新 更多