Step4 - Python基礎4 迭代器、裝飾器、軟體開發規範

來源:互聯網
上載者:User

標籤:return   附加   代碼   nbsp   方式   無法   本質   stop   sleep   

1.裝飾器

定義:本質是函數,就是為其他函數添加附加功能

原則:1.不能修改被裝飾的函數的原始碼

   2.不能修改被裝飾的函數的調用方式

例子:

import timedef timer(func):    def warpper(*args,**kwargs):        start_time = time.time()        func()        stop_time = time.time()        print("the func run time is %s" % (stop_time-start_time))    return warpper@timer #實際功能相當於func1 = timer(func1)def func1():    time.sleep(3)    print("in the test1")func1()#結果#in the test1#the func run time is 3.0005111694335938

該函數滿足裝飾器的所有要求

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

高階函數:

把一個函數名當做實參傳給另外一個函數;傳回值中包含函數名

def func1(func):    print(func)def func2():    print(1)func1(func2)

嵌套函數:

在一個函數的函數體內定義另一個函數

def func1():    print("in the func1")    def func2():        print("in the func2")    func2()func1()

我的理解:

裝飾器的實現方式,本質就是改變原函數的記憶體位址。通過高階函數的傳回值,將嵌套函數的記憶體位址賦給了原函數,而原函數的功能被記錄在了嵌套函數中,通過嵌套函數添加了新功能,而且不改變原始碼及原函數的調用方式。func1函數實際上已經變成了warpper函數,warpper函數的功能=func1原來的功能+添加的功能。但是func1的功能將會被永遠改變,無法再單獨實現func1的功能。

那如果函數要傳參數進去怎麼辦呢?

簡單!加個非固定參數就搞定了!

import timedef timer(func):    def warpper(*args, **kwargs):        start_time = time.time()        func(*args, **kwargs)        stop_time = time.time()        print("the func run time is %s" % (stop_time - start_time))    return warpper@timerdef func1():    time.sleep(1)    print("in the test1")@timerdef func2(*args, **kwargs):    print(args, kwargs)func1()func2("Nick", daizhi="22", sex="male")

 

Step4 - Python基礎4 迭代器、裝飾器、軟體開發規範

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.