閉包的定義:
閉包(Closure)是詞法閉包(Lexical Closure)的簡稱,是引用了自由變量的函數。這個被引用的自由變量將和這個函數一同存在,即使已經離開了創造它的環境也不例外。所以,閉包是由函數和與其相關的引用環境組合而成的實體。
#! /usr/bin/env python def closuretesting(): b = 15 c = 20 print 'b id %x'% id(b) print 'c id %x'% id(c) def line(x): return 2*x + b + c return line testline=closuretesting() print(testline.__closure__) # 這個屬性中的值,你會發現正好爲b 和 c 的ID ,因此可以得知,閉包是通過這個屬性去記錄類似於b,c這樣的變量的 print(testline.__closure__[0].cell_contents) # __closure__裏包含了一個元組(tuple),這個元組中的每個元素是cell類型的對象 print(testline.__closure__[1].cell_contents) print(testline(10))
output
b id 1026008 c id 1025f90 (<cell at 0x7f5efed66d38: int object at 0x1026008>, <cell at 0x7f5efed66d70: int object at 0x1025f90>) 15 20 55
閉包的判斷:
(1)一個嵌套函數(函數裏面的函數)
(2)嵌套函數用到封閉函數裏定義的一個或多個值
(3)封閉函數的返回值是嵌套函數
參考文章:http://python.jobbole.com/82296/