首頁 > 後端開發 > Python教學 > Python中nonlocal關鍵字

Python中nonlocal關鍵字

高洛峰
發布: 2016-10-20 09:42:53
原創
2378 人瀏覽過

在這篇文章中介紹了「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  

更多參考資料:

1. http://stackoverflow.com/questions/1261875/python-nonlocal-statement

2.javascript中作用域鏈定義與python作用域的異同

3.官方文件:

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.「

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板