加nonlocal:
count = 10
def non_local_test():
count = 100
def inner():
nonlocal count
count = 1000
print('inner count is {}'.format(count))
inner()
print('outside count is {}'.format(count))
non_local_test()
print('global count is {}'.format(count))
结果:
不加nonlocal:
count = 10
def non_local_test():
count = 100
def inner():
count = 1000
print('inner count is {}'.format(count))
inner()
print('outside count is {}'.format(count))
non_local_test()
print('global count is {}'.format(count))
结果:
细心的小伙伴就会发现中间有个值不一样,nonlocal声明的变量不是局部变量,也不是全局变量
,而是外部嵌套函数内的变量。当一个函数在本地作用域找不到变量申明时会向外层函数寻找,这在函数闭包中很常见,但是在不加nonlocal的情况下是不能就行修改的:
另外这个nonlocal应该是python3中才加入的