Python函數(八)-裝飾器(一)
阿新 • • 發佈:2018-02-02
裝飾器 lee author brush light log 裝飾 true 源代碼
裝飾器通過函數來定義,用來裝飾函數
裝飾器不改變被裝飾函數的源代碼和運行方式
如何實現這個效果呢?
# -*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR" import time def timer(func): #定義一個裝飾器 def deco(): start_time = time.time() func() stop_time = time.time() print("the run time is %s"%(stop_time-start_time)) return deco def test1(): time.sleep(3) print(‘in the test1‘) test1 = timer(test1) test1()
既沒有改變被裝飾函數的源代碼,也沒有改變它的運行方式
運行
這麽寫有些復雜,可以直接在函數前調用裝飾器
調用裝飾器的格式為:@裝飾器名
# -*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR" import time def timer(func): #定義一個裝飾器 def deco(): start_time = time.time() func() stop_time = time.time() print("the run time is %s"%(stop_time-start_time)) return deco @timer #相當於test1 = timer(test1) def test1(): time.sleep(3) print(‘in the test1‘) test1()
運行
執行過程:
先走test1函數前的裝飾器timer(),然後在timer()函數內走函數deco(),記錄下start_time,然後deco()函數調用函數test1(),然後執行完函數test1()後,記錄下stop_time,最後計算時間並打印
Python函數(八)-裝飾器(一)