global 定义全局变量,必须先声明,在使用
例如:global a #声明全局变量
a = a+1
locals() 获取本函数作用域中的局部变量(函数即变量)
nonlocal 必须在整个嵌套函数作用域内定义局部变量,获取上层函数的变量
例如:
1.
def test():
a = 1
def test1():
nonlocal a #必须先声明
a = a+1
print (a)
return test1
t = test()
t()
打印a = 2
2.
def test():
a = 1
def test1():
def test2():
nonlocal a
a = a + 1
print (a)
return test2
return test1
t = test()
print(t)
a = t()
a()
打印a = 2
如果nonlocal的外层函数没有定义局部变量,则报错
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。