再談裝飾器
點擊上方藍色字體,關(guān)注程序員zhenguo

你好,我是 zhenguo
回答關(guān)于裝飾器的幾個典型問題。
1 問題
大概問題是這樣,想要自定義一個Python裝飾器,問我這樣寫裝飾器行不行?如果不行,那又是為什么?
import?datetime
import?time
def?print_time(g):
????def?f():
????????print('開始執(zhí)行時間')
????????print(datetime.datetime.today())
????????
????????g()
????????
????????print('結(jié)束時間')
????????print(datetime.datetime.today())
????f()
下面使用 print_time裝飾函數(shù) foo:
@print_time
def?foo():
????time.sleep(2)
????print('hello?world')
當(dāng)調(diào)用 foo函數(shù)時,拋出如下異常:
foo()
---------------------------------------------------------------------------
TypeError?????????????????????????????????Traceback?(most?recent?call?last)
-27-c19b6d9633cf>?in?
---->?1?foo()
TypeError:?'NoneType'?object?is?not?callable
所以,按照如上定義 print_time裝飾器,肯定是不行的。
2 為什么不行
要想明白為啥不行,首先要知道裝飾器這個語法的本質(zhì)。其實很簡單,@print_time裝飾foo函數(shù)等于:
foo?=?print_time(foo)
就是這一行代碼,再也沒有其他。
因為上面的 print_time 無返回值,所以賦值給 foo 函數(shù)后,foo 函數(shù)變?yōu)?None,所以當(dāng)調(diào)用 foo() 時拋出 'NoneType' object is not callable
這也就不足為奇了。
3 應(yīng)該怎么寫
print_time 需要返回一個函數(shù),這樣賦值給 foo函數(shù)后,正確寫法如下所示:
import?datetime
import?time
def?print_time(g):
????def?f():
????????print('開始執(zhí)行時間')
????????print(datetime.datetime.today())
????????
????????g()
????????
????????print('結(jié)束時間')
????????print(datetime.datetime.today())
????return?f
裝飾 foo:
@print_time
def?foo():
????time.sleep(2)
????print('hello?world')
調(diào)用 foo ,運行結(jié)果如下:
foo()
開始執(zhí)行時間
2021-04-02?22:32:49.114124
hello?world
結(jié)束時間
2021-04-02?22:32:51.119506
一切正常
4 裝飾器好處
上面自定義print_time裝飾器,除了能裝飾foo函數(shù)外,還能裝飾任意其他函數(shù)和類內(nèi)方法。
裝飾任意一個函數(shù) foo2:
@print_time
def?foo2():
??print('this?is?foo2')
裝飾類內(nèi)方法 foo3,需要稍微修改原來的print_time:
????def?print_time(g):
????????def?f(*args,?**kargs):
????????????print('開始執(zhí)行時間')
????????????print(datetime.datetime.today())
????????
????????????g(*args,?**kargs)
????????
????????????print('結(jié)束時間')
????????????print(datetime.datetime.today())
????????return?f
為類MyClass中foo3方法增加print_time裝飾:
class?MyClass(object):
????@print_time
????def?foo3(self):
????????print('this?is?a?method?of?class')
執(zhí)行結(jié)果如下:
MyClass().foo3()
開始執(zhí)行時間
2021-04-02?23:16:32.094025
this?is?a?method?of?class
結(jié)束時間
2021-04-02?23:16:32.094078
以上就是裝飾器的通俗解釋,平時可以多用用,讓我們的代碼更加精煉、可讀。
對應(yīng)關(guān)鍵詞下載評論
圖片
表情
