全局变量报错:UnboundLocalError: local variable 'l' referenced before assignment

总结:
  1. 内部函数,不修改全局变量可以访问全局变量
  2. 内部函数,修改同名全局变量,则python会认为它是一个局部变量
  3. 在内部函数修改同名全局变量之前调用变量名称(如print sum),则引发Unbound-LocalError
在程序中设置的sum属于全局变量,而在函数中没有sum的定义,根据python访问局部变量和全局变量的规则:当搜索一个变量的时候, python先从局部作用域开始搜索,如果在局部作用域没有找到那个变量,那样python就在全局变量中找这个变量,如果找不到抛出异常(NAMEERROR或者Unbound-LocalError,这取决于python版本。)

如果内部函数有引用外部函数的同名变量或者全局变量,并且对这个变量有修改.那么python会认为它是一个局部变量,又因为函数中没有sum的定义和赋值,所以报错。

测试:

import threading
import time

COUNT=10

def printHello():
	print(COUNT)
	COUNT = COUNT -1

def main():
	threads = []
	for i in range(0,1):
		t = threading.Thread(target=printHello)
		threads.append(t)
	for t in threads:
		t.start()
	for t in threads:
		t.join()

if __name__ == '__main__':
	main()
报错:UnboundLocalError: local variable 'COUNT' referenced before assignment


import threading
import time

LOCK = threading.Lock()
COUNT=10

def printHello():
	global COUNT
	print(COUNT)
	LOCK.acquire()
	COUNT = COUNT -1
	LOCK.release()

def main():
	threads = []
	for i in range(0,10):
		t = threading.Thread(target=printHello)
		threads.append(t)
	for t in threads:
		t.start()
	for t in threads:
		t.join()

if __name__ == '__main__':
	main()

运行正确

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值