標籤:
閉包:是由函數和其他相關的引用環境組合而成的實體。
如果一個函數內部,對在外部範圍的變數進行引用,那麼內建函式就被認為是閉包(closure)。
A CLOSURE is a function object that remembers values in enclosing scopes regardless of whether those scopes are still present in memory.
>>> def hellocounter(name):
count=[0]
def counter():
count[0]+=1
print "Hello,",name,‘,‘,str(count[0])," access"
return counter
>>> hello = hellocounter("zxahu")
>>> hello()
Hello, zxahu , 1 access
>>> hello()
Hello, zxahu , 2 access
這裡,counter()中調用了外部的變數,所以它這裡是閉包
__closure__ 屬性返回一組cell object,它包含了在閉包環境中的變數,注意,如果變數是引用,那麼cell中儲存的就是引用,如果是不可變得變數,那麼存的是變數
>>> hello.__closure__
(<cell at 0x02DF2FD0: list object at 0x02DF4DA0>, <cell at 0x02E057B0: str object at 0x02E057C0>)
>>> hello.__closure__[0].cell_contents
[2]
>>> hello.__closure__[1].cell_contents
‘zxahu‘
裝飾器“@”decorator
若要增強某函數的功能,但又不希望修改該函數的定義,這種代碼運行期間動態增加功能的方式,稱為裝飾器
def deco(func):
def __decorator():
print "decorator running... prepare function"
func()
print "function done"
return __decorator
@deco
def test():
print "test func running..."
test()
輸出:
decorator running... prepare function
test func running...
function done
python 閉包 裝飾器