当我使用两个交互的全局字典(在我的例子中,Counters)时,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: local variable 'daily_detections' referenced before assignment(在赋值前引用了局部变量'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()
输出的结果是:
Counter({'鼠标': 3, '狗': 2, '猫': 1})
Counter({'鼠标': 3, '狗': 2, '猫': 1})
谁能解释一下这种行为,以及如何最好地避免它?
不要忘记使用 global daily_detections
和 global hourly_detections
在每个函数中。
Python 认为这些都是局部变量,除非你在函数开始时声明它们为 globals,然后在你试图执行 hourly_detections['cat'] += 1
你基本上是想在 "一个非初始化变量 "中添加一个变量。
你也可以把它们作为函数参数发送,因为这被认为是更好的做法(请阅读 此处).