關鍵字nonlocal:是python3.X中出現(xiàn)的,所以在python2.x中無法直接使用.
python引用變量的順序為: 當前作用域局部變量->外層作用域變量->當前模塊中的全局變量->python內置變量
python中關鍵字nonlocal和global區(qū)別:
一:global關鍵字用來在函數(shù)或其它局部作用域中使用全局變量驮捍。但是如果不使用全局變量也可以不適用global關鍵字聲明。
In [1]: gcount = 0
In [2]: def get_global():
...: #不修改時正林,不用使用global關鍵字
...: return gcount
...:
In [3]: def global_add():
...: #修改時色徘,需要使用global關鍵字
...: global gcount
...: gcount += 1
...: return gcount
...:
In [4]: get_global()
Out[4]: 0
In [5]: global_add()
Out[5]: 1
In [6]: global_add()
Out[6]: 2
In [7]: get_global()
Out[7]: 2
二:nonlocal關鍵字用來在函數(shù)或其它作用域中使用外層(非全局)變量
In [8]: def make_counter():
...: count = 0
...: def counter():
...: nonlocal count
...: count += 1
...: return count
...: return counter
...:
In [9]: counter = make_counter()
In [10]: counter()
Out[10]: 1
In [11]: counter()
Out[11]: 2
在python2中可以設置可變變量來實現(xiàn)沫换,例如列表软驰,字典等。