新聞中心
這篇文章主要講解了“如何正確用裝飾器”,文中的講解內(nèi)容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“如何正確用裝飾器”吧!
創(chuàng)新互聯(lián)公司自成立以來,一直致力于為企業(yè)提供從網(wǎng)站策劃、網(wǎng)站設(shè)計、成都網(wǎng)站制作、成都網(wǎng)站設(shè)計、電子商務(wù)、網(wǎng)站推廣、網(wǎng)站優(yōu)化到為企業(yè)提供個性化軟件開發(fā)等基于互聯(lián)網(wǎng)的全面整合營銷服務(wù)。公司擁有豐富的網(wǎng)站建設(shè)和互聯(lián)網(wǎng)應用系統(tǒng)開發(fā)管理經(jīng)驗、成熟的應用系統(tǒng)解決方案、優(yōu)秀的網(wǎng)站開發(fā)工程師團隊及專業(yè)的網(wǎng)站設(shè)計師團隊。
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')
當調(diào)用 foo函數(shù)時,拋出如下異常:
foo() --------------------------------------------------------------------------- TypeError Traceback (most recent call last)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,所以當調(diào)用 foo() 時拋出 'NoneType' object is not callable
這也就不足為奇了。
3. 應該怎么寫
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
以上就是裝飾器的通俗解釋,平時可以多用用,讓我們的代碼更加精煉、可讀。
感謝各位的閱讀,以上就是“如何正確用裝飾器”的內(nèi)容了,經(jīng)過本文的學習后,相信大家對如何正確用裝飾器這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是創(chuàng)新互聯(lián),小編將為大家推送更多相關(guān)知識點的文章,歡迎關(guān)注!
當前標題:如何正確用裝飾器
網(wǎng)頁URL:http://www.ef60e0e.cn/article/jhispd.html