nonlocal 用来指定上一层变量
>>> str = "nihao"
>>> def test1():
str = "hello"
def test2():
nonlocal str
str = "world"
test2()
print(str)
>>> print(str)
nihao
>>> test1()
world
>>> #这里使用global来修改全局变量,使用nonlocal来修改上一级的变量,即hello被修改为world
nonlocal 用来指定上一层变量
>>> str = "nihao"
>>> def test1():
str = "hello"
def test2():
nonlocal str
str = "world"
test2()
print(str)
>>> print(str)
nihao
>>> test1()
world
>>> #这里使用global来修改全局变量,使用nonlocal来修改上一级的变量,即hello被修改为world