標籤:定義 變數 state 存在 local 如何 stat 方法 nested
nonlocal關鍵字時Python 3.X中引入的,目的是讓內層函數可以修改外層函數的變數值,而該關鍵字在Python 2.X中是不存在的。那麼,要在Python 2.X中達到類型達到類似nonlocal關鍵字的效果,有方法嗎?
答案是肯定的,主要有如下四種方法:
1 將要改變的變數在外層函式宣告成global的,這樣內層函數就可以改變這個變數的值了,缺點就是所有內層函數都共用一個全域變數的值:
def test(start): global state # 將state聲明成全域變數 state = start def nested(label): global state # 必須使用global再次聲明,否則state += 1會報錯,因此不使用global聲明,Python認為state是在nested裡面聲明的一個局部變數,而這個變數沒有被定義(即沒有被賦值),就被拿來使用了 print(label, state) state += 1 return nested>>>F = test(1)>>>F(‘toast‘)toast 1>>> G = test(42)>>>G(‘spam‘)spam 42>>>F(‘ham‘) # F和G都共用一個全域變數state,導致F的state變成了43ham 43
2 使用class
class tester: def __init__(self, start): self.state = start def nested(self, label): print(label, self.state) self.state += 1 >>>F = test(0)>>>F.nested(‘spam‘)spam 0
3 使用函數的屬性,由於函數在Python裡面是一個對象,因此可以給它添加屬性,我們可以利用這一點達到目的
def tester(start): def nested(label): print(label, nested.state) nested.state += 1 nested.state = start # state作為函數屬性 return nested
4 利用可變的資料結構,比如數組,但是相比較使用class和函數的屬性,這種使用方式很晦澀
def tester(start): def nested(label): print(label, state[0]) state[0] += 1 state = [start] # 通過數組達到這一目的 return nested
如何在Python 2.X中也達到類似nonlocal關鍵字的效果