python中nonlocal和global的区别

python中nonlocal和global的区别

1,global
global定义全局变量 这个适用于全局
例如

count=0
def sums():
	global count
	count+=1
sums()
print(count)

结果为 1
2,nonlocal
nonlocal用于外部嵌套变量的调用

def tree():
	count=0
	def sums():
		nonlocal count
		count+=1
	sums()
	print(count)
tree()

结果为 1

猜你喜欢

转载自blog.csdn.net/qq_44671932/article/details/109250968