python學習【第四篇】python函數 (二)

來源:互聯網
上載者:User

標籤:修改   原則   外部   ret   star   %s   end   分享圖片   ide   

一、裝飾器

裝飾器:本質就是函數,功能是為其它函數添加附加功能

裝飾器的原則:

  • 不修改被修飾函數的原始碼
  • 不修改被修飾函數的調用方式

裝飾器的知識儲備:

  裝飾器 = 高階函數 + 函數嵌套 + 閉包

 

二、高階函數

高階函數的定義:

  • 函數的接收參數是一個函數名
  • 函數的傳回值是一個函數名
  • 滿足上述條件任意一個都可以是高階函數
import timedef fun1():    time.sleep(0.5)    print("hello")def computing_run_time(fun):    """    計算函數已耗用時間    :param fun:     :return:     """    start_time = time.time()    fun()    end_time = time.time()    print("已耗用時間%s" % (end_time - start_time))computing_run_time(fun1)"""優點:在不修改函數原始碼的前提下,給函數添加了額外的功能缺點:改變了調用方式"""
函數的接收參數是函數名
import timedef fun1():    time.sleep(0.5)    print("hello")def computing_run_time(fun):    """    計算函數已耗用時間    :param fun:     :return:     """    fun()    return funfun1 = computing_run_time(fun1)fun1()   """優點:沒有改變函數的調用方式缺點:不能為函數添加新的功能"""
函數的傳回值是函數名

註:僅僅是高階函數不能滿足裝飾器的需求

三、函數嵌套和閉包
"""閉包:首先必須是內部定義的函數,該函數包含對外部範圍而不是全域範圍名字的引用定義:內建函式的程式碼封裝含對外部函數的代碼的引用,但一定不是對全域範圍的引用"""def fun1():    print("fun1")    name = 1    def fun2():        print("fun2")        print(name)        def fun3():            print("fun3")            print(name)        fun3()    fun2()fun1()

  

  

 

python學習【第四篇】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.