Python裝飾函數
阿新 • • 發佈:2017-12-29
col his 語句 pri body 裝飾 span this class
from time import ctime, sleep def tsfunc(func): def wrappedFunc(): print(‘[%s] %s() classed‘ % (ctime(),func.__name__)) print("先執行裝飾器") return func() print("this is tsfunc") return wrappedFunc @tsfunc def foo(): print("this is foo") @tsfuncdef foo2(): print("this is foo2") foo(); foo2();
運行結果
this is tsfunc this is tsfunc [Fri Dec 29 20:48:34 2017] foo() classed 先執行裝飾器 this is foo [Fri Dec 29 20:48:34 2017] foo2() classed 先執行裝飾器 this is foo2 [Finished in 0.2s]
調用foo()以後,
裝飾器中的語句先執行了。
然後開始調用內部函數,執行內部函數的語句
然後開始執行被裝飾函數的語句
Python裝飾函數