本文實例講述了Python閉包的用法。分享給大家供大家參考,具體如下:
Python函數中也可以定義函數,也就是閉包。跟js中的閉包概念其實差不多,舉個Python中閉包的例子。
def make_adder(addend): def adder(augend): return augend + addend return adderp = make_adder(23)q = make_adder(44)print(p(100))print(q(100))
運行結果是:123和144.
為什么?Python中一切皆對象,執行p(100),其中p是make_adder(23)這個對象,也就是addend這個參數是23,你又傳入了一個100,也就是augend參數是100,兩者相加123并返回。
有沒有發現make_adder這個函數,里面定義了一個閉包函數,但是make_adder返回的return卻是里面的這個閉包函數名,這就是閉包函數的特征。
再看一個Python閉包的例子:
def hellocounter (name): count=[0] def counter(): count[0]+=1 print('Hello,',name,',',count[0],' access!') return counterhello = hellocounter('ma6174')hello()hello()hello()
運行結果:
tantengdeMacBook-Pro:learn-python tanteng$ python3 closure.py Hello, ma6174 , 1 access!Hello, ma6174 , 2 access!Hello, ma6174 , 3 access!
使用閉包實現了計數器的功能,這也是閉包的一個特點,返回的值保存在了內存中,所以可以實現計數功能。
轉自:小談博客 http://www.tantengvip.com/2015/07/python-closure/
希望本文所述對大家Python程序設計有所幫助。