nonlocal关键字用来在函数或其余做用域中使用外层(非全局)变量。python
>>> def outer(): x = 1 def inner(): nonlocal x x = 2 print("inner:", x) inner() print("outer:", x) >>> outer() inner: 2 outer: 2
Python2.x解决函数引用外层变量的方法只有使用global 关键字定义全局变量,另外一种可行的解决方案是使用列表或字典代替要操做的关键字函数
>>> def outer(): x = [1] def inner(): x[0] += 1 #修改x[0]保存的值 print("inner:", x[0]) inner() print("outer:", x[0]) >>> outer() inner: 2 outer: 2