如何在Python 2.X中也達到類似nonlocal關鍵字的效果

來源:互聯網
上載者:User

標籤:定義   變數   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關鍵字的效果

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.