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