在這篇文章中介紹了「Python的閉包與nonlocal」的用法,因為nonlocal是在Python3.0中新增的關鍵字,python2.x不提供支持,文中提出在Python2.x解決嵌套函數引用外部變數的方法只有使用global 關鍵字定義全域變量,另一種可行的解決方案是使用列表或字典來取代要操作的關鍵字。
範例如下:
1.python3.0 使用nonlocal關鍵字
>>> def outer(): x = 1 def inner(): nonlocal x x = 2 print("inner:", x) inner() print("outer:", x) >>> outer() inner: 2 outer: 2
2.python2.x
2.python2.x
更多參考資料:
listed identifiers to refer to previously bound variables in the nearest enclosing scope. This is important because the default behavior for binding is to search the local namespace first. The statement allows encapsulated search the local namespace first. The statement tos encapsulated sabled respeside sables mulca. scope.
Names listed in a nonlocal statement, unlike to those listed in a global statement, must refer to pre-existing bindings in an enclosing scope (the scope in which a new binding bindings in 是 enclosing scope (the scope in which a new binding be created unding Names listed in a nonlocal statement must not collide with pre-existing bindings in the local scope.「