Python閉包
閉包叫lexical closure(詞法閉包),指函數及相關的環境所組成的整體。內部的稱爲函數,外部的稱爲環境,外層給內層函數提供一個運行環境。
如例1中f1的主要目的是爲f2提供運行環境。
在函數內部定義一個子函數,該子函數並未被調用,而是直接作爲一個返回值返回,從而達到閉合函數的效果,稱爲Python閉合函數。
具備變量公用、隱藏狀態、函數對象和作用域隨意切換、一個函數實現多種功能的特性
例1:
In [1]: def f1():
...: x = 666
...: def f2():
...: y = "hello world"
...: print x,y
...: return f2
In [2]: f1()
Out[2]:
In [3]: a1 = f1()
In [4]: type(a1)
Out[4]: function
In [5]: a1()
666 hello world
例2:
In [1]: def f1(x):
...: def f2(y):
...: return x ** y
...: return f2
In [2]: f1(4)
Out[2]:
In [3]: f4 = f1(4)
In [4]: type(f4)
Out[4]: function
In [5]: f4(1)
Out[5]: 4
In [6]: f4(2)
Out[6]: 16
In [7]: f4(3)
Out[7]: 64
In [8]: f4 = f1(3)
In [9]: f4(1)
Out[9]: 3
In [10]: f4(2)
Out[10]: 9
In [11]: f4(3)
Out[11]: 27
例3:構建函數,使其在給定起始位置,能給出軌跡改變後的位置
In [1]: def startPos(x,y):
...: def newPos(m,n):
...: print "The start position is (%d,%d) ,The new position is (%d,%d)."% (x,y,x+m,y+n)
...: return newPos
In [2]: action = startPos(10,10)
In [3]: action(-2,12)
The start position is (10,10) ,The new position is(8,22).
In [4]: action(8,12)
The start position is (10,10) ,The new position is(18,22).
In [5]: action = startPos(18,22)
In [6]: action(8,12)
The start position is (18,22) ,The new position is(26,34).