關(guān)鍵字nonlocal:是python3.X中出現(xiàn)的,所以在python2.x中無法直接使用.
python引用變量的順序?yàn)椋?當(dāng)前作用域局部變量->外層作用域變量->當(dāng)前模塊中的全局變量->python內(nèi)置變量
python中關(guān)鍵字nonlocal和global區(qū)別:
一:global關(guān)鍵字用來在函數(shù)或其它局部作用域中使用全局變量。但是如果不使用全局變量也可以不適用global關(guān)鍵字聲明。
In [1]: gcount = 0
In [2]: def get_global():
...: #不修改時(shí),不用使用global關(guān)鍵字
...: return gcount
...:
In [3]: def global_add():
...: #修改時(shí),需要使用global關(guān)鍵字
...: 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關(guān)鍵字用來在函數(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中可以設(shè)置可變變量來實(shí)現(xiàn),例如列表,字典等。