【Python裝飾者】在函數測試的作用

來源:互聯網
上載者:User

標籤:self   res   time()   ima   function   ret   imp   測試的   for   

【引言】我們經常需要多函數進行耗時測試,測試方法有許多,這裡介紹裝飾者的方法,提高耗時測試代碼的可複用性,在其他方面的應用也是如此。【設計原則】類應該對擴充開放,對修改關閉。【代碼】(1)定義裝飾者具體方法
#encoding: UTF-8‘‘‘Created on 2016??12??7??@filename: test.py@author: YYH‘‘‘import timefrom functools import wraps class TimeRecorder:def __init__(self, name="function"):print(name +"()"+ " Start...")print(name +"()"+ " Running...")self.name = nameself.startTime = time.time()def __del__(self):print("{0}() Ended,Cost Time:{1} s".format(self.name, time.time() - self.startTime))#使用裝飾者測試函數已耗用時間,這裡看起來像是“鉤子”的方法,實際並不是的,藉助於Python的裝飾者,這個方法將發揮巨大的作用。def fn_timer(function):@wraps(function) #解決列印函數名的bugdef function_timer(*args, **kwargs):tR=TimeRecorder(function.__name__) #增加變數,由使得該對象的生命器存在整個函數result = function(*args, **kwargs)return resultreturn function_timer

 

(2)定義裝飾者(該方法就就具有fn_timer的“能力”)(3)使用裝飾者
(4)結果

【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.