版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_41402059/article/details/82287568
函数的嵌套定义:
def outer():
print('outer')
def inner():
print('inner')
outer() # outer
global只声明全局变量,不管函数嵌套多少层,如果想改变最近一层局部变量,使用nonlocal,如果找不到上层局部变量会报错
a = 1
def outer():
a = 2
def inner():
global a
a += 1
inner()
outer()
print(a) # 2
a = 1
def outer():
a = 2
def inner():
nonlocal a
a += 1
inner()
print('outer->a',a)
outer() # outer->a 3