本文研究的主要內容是Python中裝飾器相關學習總結,具體如下。
from time import ctime, sleepdef timefun(func): def wrappedfunc(): print("%s called at %s"%(func.__name__, ctime())) func() return wrappedfunc@timefundef foo(): print("I am foo")foo()sleep(2)foo()分析如下:
上面代碼理解裝飾器執行行為可理解成
foo = timefun(foo)
1,foo先作為參數賦值給func后,foo接收指向timefun返回的wrappedfunc
2,調用foo(),即等價調用wrappedfunc()
3,內部函數wrappedfunc被引用,所以外部函數的func變量(自由變量)并沒有釋放
4,func里保存的是原foo函數對象
例2:被裝飾的函數有參數
from time import ctime, sleepdef timefun(func): def wrappedfunc(a, b): print("%s called at %s"%(func.__name__, ctime())) print(a, b) func(a, b) return wrappedfunc@timefundef foo(a, b): print(a+b)foo(3,5)sleep(2)foo(2,4)例3:被裝飾的函數有不定長參數
from time import ctime, sleepdef timefun(func): def wrappedfunc(*args, **kwargs): print("%s called at %s"%(func.__name__, ctime())) func(*args, **kwargs) return wrappedfunc@timefundef foo(a, b, c): print(a+b+c)foo(3,5,7)sleep(2)foo(2,4,9)例4:裝飾器中的return
from time import ctime, sleepdef timefun(func): def wrappedfunc(): print("%s called at %s"%(func.__name__, ctime())) func() return wrappedfunc@timefundef foo(): print("I am foo")@timefundef getInfo(): return '----hahah---'foo()sleep(2)foo()print(getInfo())執行結果:
foo called at Sun Jun 18 00:31:53 2017
I am foo
foo called at Sun Jun 18 00:31:55 2017
I am foo
getInfo called at Sun Jun 18 00:31:55 2017
None如果修改裝飾器為return func(),則運行結果:
foo called at Sun Jun 18 00:34:12 2017
I am foo
foo called at Sun Jun 18 00:34:14 2017
I am foo
getInfo called at Sun Jun 18 00:34:14 2017
----hahah---
小結:一般情況下為了讓裝飾器更通用,可以有return
例5:裝飾器帶參數,在原有裝飾器的基礎上,設置外部變量
from time import ctime, sleepdef timefun_arg(pre="hello"): def timefun(func): def wrappedfunc(): print("%s called at %s %s"%(func.__name__, ctime(), pre)) return func() return wrappedfunc return timefun@timefun_arg("itcast")def foo(): print("I am foo")@timefun_arg("python")def too(): print("I am too")foo()sleep(2)foo()too()sleep(2)too()可以理解為foo()==timefun_arg("itcast")(foo)()
新聞熱點
疑難解答