標籤:top log func 技術 通過 python 複雜 inf class
裝飾器通過函數來定義,用來裝飾函數
裝飾器不改變被裝飾函數的原始碼和運行方式
如何?這個效果呢?
# -*- coding:utf-8 -*-__author__ = "MuT6 Sch01aR"import timedef timer(func): #定義一個裝飾器 def deco(): start_time = time.time() func() stop_time = time.time() print("the run time is %s"%(stop_time-start_time)) return decodef test1(): time.sleep(3) print(‘in the test1‘)test1 = timer(test1)test1()
既沒有改變被裝飾函數的原始碼,也沒有改變它的運行方式
運行
這麼寫有些複雜,可以直接在函數前調用裝飾器
調用裝飾器的格式為:@裝飾器名
# -*- coding:utf-8 -*-__author__ = "MuT6 Sch01aR"import timedef 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函數(八)-裝飾器(一)