1、打开Python开发工具IDLE,新建‘testNonloc.py’文件。
2、在testNonloc.py文件中写代码如下:def test1(): t1 = 'abc' print ('test1:%s'稆糨孝汶; %(t1)) def test2(): print (t1) return test2t2 = test1()t2()test1是外层函数,test2是内层函数。
3、F5运行代码,结果如下图所示,外层函数打印出外层函数内定义的变量t1的值,内层函数也能打印出外层函数中定义的t1的值。
4、修改变量定义的位置,在内层函数定义变量,代码如下:def test1(): print ('test1:%s' %(t2)) def test2(): t2 = 'abc' print (t2) return test2t2 = test1()t2()
5、F5运行代码,程序报错,因为在外层函数无法访问到内层函数定义的变量。
6、修改代码,使用nonlocal蠹韦睥谚声明内层函数中定义的变量,代码如下:def test1(): t2 = 'a' print ('test1:%s' %(t2)) def test2(): nonlocal t2 t2 = 'abc' print (t2) test2() print (t2) test1()
7、F5运行代码,发现在内层函数可以正常修改nonlocal关键字声明的外层函数定义的变量。总结一下nonlocal关键字使用场景是内层函数修改外层函数的变量,global关键字使用场景是任意函数修改全局变量。