標籤:外部類 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函數的閉包