Python # 裝飾器
阿新 • • 發佈:2017-09-15
als style div turn 通過 sta () pre ndt
###
現在我有一個簡單的myfunc函數,現在我想對myfunc函數增加功能。下面我們增加一個deco的功能。
import time def deco(func): startTime = time.time() func() endTime = time.time() msecs = (endTime - startTime) print("-->elapsed time %s s"%msecs) def myfunc(): print(‘start myfunc‘) time.sleep(3) print(‘end myfunc‘) deco(myfunc)
但是這種方式存在一個問題,修改了myfunc的原來的調用方式:myfunc() ------> 變成了 deco(myfunc)。所以我們做了下面的改變。
###
def deco(func): def wrapper(): startTime = time.time() func() endTime = time.time() msecs = (endTime - startTime) print("-->elapsed time %s s"%msecs)return wrapper ###返回的是<function deco.<locals>.wrapper at 0x03234468> 可以通過wrapper()調用
def myfunc():
print(‘start myfunc‘)
time.sleep(3)
print(‘end myfunc‘)
print("myfunc is %s"%myfunc.__name__ )
myfunc=deco(myfunc)
print("myfunc is %s"%myfunc.__name__ )
myfunc()
輸出結果:
myfunc is myfunc
myfunc is wrapper
start myfunc
end myfunc
-->elapsed time 3.0007433891296387 s
經過了上面的改動後,一個比較完整的裝飾器(deco)就實現了,裝飾器沒有影響原來的函數,以及函數調用的代碼。
例子中值得註意的地方是,Python中一切都是對象,函數也是,所以代碼中改變了”myfunc”對應的函數對象。
###
def deco(func): def wrapper(): startTime = time.time() func() endTime = time.time() msecs = (endTime - startTime) print("-->elapsed time %s s"%msecs) return wrapper @deco def myfunc(): print(‘start myfunc‘) time.sleep(3) print(‘end myfunc‘) myfunc()
###
Python # 裝飾器