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") @tsfunc def 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()以後,
裝飾器中的語句先執行了。
然後開始呼叫內部函式,執行內部函式的語句
然後開始執行被裝飾函式的語句