为什么在 Python 中交互的两个全局词典会抛出局部引用错误?

Why do two global dictionaries interacting in Python throw a local reference error?

当我使用两个交互的全局字典(在我的例子中是计数器)时,Python 抛出一个局部引用错误。为了说明这个问题,这里是示例代码:

from collections import Counter

hourly_detections = Counter()
daily_detections = Counter()

def populate_hourly():
    hourly_detections['cat'] += 1
    hourly_detections['dog'] += 2
    hourly_detections['mouse'] += 3

def populate_daily():
    daily_detections += hourly_detections

def run():
    populate_hourly()
    populate_daily()

    print(hourly_detections)
    print(daily_detections)

if __name__ == '__main__':
    run()

此代码在 populate_daily 函数中抛出以下错误:UnboundLocalError:局部变量 'daily_detections' 在赋值前被引用

但是,如果我们在populate_daily函数中添加专门针对daily_detections的全局标志,代码将完美运行:

from collections import Counter

hourly_detections = Counter()
daily_detections = Counter()

def populate_hourly():
    hourly_detections['cat'] += 1
    hourly_detections['dog'] += 2
    hourly_detections['mouse'] += 3

def populate_daily():
    global daily_detections
    daily_detections += hourly_detections

def run():
    populate_hourly()
    populate_daily()

    print(hourly_detections)
    print(daily_detections)

if __name__ == '__main__':
    run()

输出为:

计数器({'mouse': 3, 'dog': 2, 'cat': 1})

计数器({'mouse': 3, 'dog': 2, 'cat': 1})

谁能解释这种行为以及如何最好地避免这种行为?

不要忘记在每个函数中使用 global daily_detectionsglobal hourly_detections

Python 认为这些是局部变量,除非您在函数的开头将它们声明为全局变量,然后在您尝试执行 hourly_detections['cat'] += 1 之后,您基本上是在尝试向 "a non initialized variable"

如果您希望将它们作为函数参数,您也可以发送它们,因为这被认为是更好的做法(请阅读 here)。