1. 程式人生 > >python函數的閉包

python函數的閉包

turn locale unbound class input div urn += 恢復

---恢復內容開始---

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 outt 12 File "<input>", line 4, in inn 13 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 outt 13 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函數的閉包