【问题标题】:Why does Python complain about reference before assignment when increasing variables in a function?为什么在函数中增加变量时,Python 在赋值之前抱怨引用?
【发布时间】:2010-10-27 07:48:00
【问题描述】:

为什么 Python 抱怨 chrome 在赋值之前被引用?它不会抱怨字典。如果它有所作为,这与 Python 2.5 一起使用。

def f():
  google['browser'] = 'chrome'
  chrome += 1

google = dict()
chrome = 1
f()

当然,我可以使它与global chrome 一起工作,但我想知道为什么 Python 不考虑分配变量。谢谢。

【问题讨论】:

    标签: python function variables


    【解决方案1】:

    在声明中

    chrome += 1
    

    它还没有被创建。 变量是在第一次分配时创建的。在这种情况下,当 python 看到代码递增 'chrome' 时,它根本看不到这个变量。

    尝试将您的代码重新排列为

    chrome = 1
    
    def f():
      global chrome
      google['browser'] = 'chrome'
      chrome += 1
    
    google = dict()
    f()
    

    【讨论】:

    • @irrelephant:谢谢。一个错字错过了全局关键字!已更正。
    • 谢谢。评论的长度必须至少为 15 个字符。
    【解决方案2】:

    超出范围:read here

    【讨论】:

      猜你喜欢
      • 2013-03-28
      • 1970-01-01
      • 2021-02-18
      • 2013-07-04
      • 2018-12-15
      • 2020-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多