python函數的閉包

來源:互聯網
上載者:User

標籤:外部類   python   lin   span   for   ref   不能   通過   變數   

---恢複內容開始---

python允許有內建函式,也就是說可以在函數內部再定義一個函數,這就會產生變數的訪問問題,類似與java的內部類,在java裡內部類可以直接存取外部類的成員變數和方法,不管是否私人,但外部類需要通過內部類的引用來進行訪問。python內建函式和外部函數的成員變數可以相互訪問但是不能修改,也就是所謂的閉包。舉個例子

 1 def outt(): 2     x=10 3     def inn(): 4         x+=1 5         return  x 6     return inn() 7          8 outt() 9 Traceback (most recent call last):10   File "<input>", line 1, in <module>11   File "<input>", line 6, in outt12   File "<input>", line 4, in inn13 UnboundLocalError: local variable ‘x‘ referenced before assignment

可以使用nonlocal 關鍵字修飾外部的成員變數使其可以被修改,具體如下

 1 def outt(): 2     x=10 3     def inn(): 4         nonlocal x 5         x+=1 6         return  x 7     return inn() 8          9 outt()10 11

對於傳的參數外函數和內函數也是閉包的 舉例如下

 1 def outt(): 2     x=10 3     def inn(y): 4         nonlocal x 5         x+=y 6         return  x 7     return inn(y) 8          9 outt()(10)10 Traceback (most recent call last):11   File "<input>", line 1, in <module>12   File "<input>", line 7, in outt13 NameError: global name ‘y‘ is not defined

但是可以簡化寫法避免傳參問題

 1 def outt(): 2     x=10 3     def inn(y): 4         nonlocal x 5         x+=y 6         return  x 7     return inn 8          9 outt()(10)10 20

可以看出外函數調用內函數時沒有在括弧裡傳參python可以對他進行預設的賦值操作,這樣就避免了參數在兩個函數之間的傳遞問題

 

python函數的閉包

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.