Python函數中的函數(閉包)用法執行個體

來源:互聯網
上載者:User
本文執行個體講述了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程式設計有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.