新聞中心
最近幾周,陸續(xù)收到幾位讀者關(guān)于裝飾器使用的提問(wèn),今天統(tǒng)一回復(fù)。

1. 問(wèn)題
大概問(wèn)題是這樣,想要自定義一個(gè)Python裝飾器,問(wèn)我這樣寫(xiě)裝飾器行不行?如果不行,那又是為什么?
- import datetime
- import time
- def print_time(g):
- def f():
- print('開(kāi)始執(zhí)行時(shí)間')
- print(datetime.datetime.today())
- g()
- print('結(jié)束時(shí)間')
- 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ù)時(shí),拋出如下異常:
- foo()
- ---------------------------------------------------------------------------
- TypeError Traceback (most recent call last)
in - ----> 1 foo()
- TypeError: 'NoneType' object is not callable
所以,按照如上定義 print_time裝飾器,肯定是不行的。
2. 為什么不行
要想明白為啥不行,首先要知道裝飾器這個(gè)語(yǔ)法的本質(zhì)。其實(shí)很簡(jiǎn)單,@print_time裝飾foo函數(shù)等于:
- foo = print_time(foo)
就是這一行代碼,再也沒(méi)有其他。
因?yàn)樯厦娴?print_time 無(wú)返回值,所以賦值給 foo 函數(shù)后,foo 函數(shù)變?yōu)?None,所以當(dāng)調(diào)用 foo() 時(shí)拋出 'NoneType' object is not callable
這也就不足為奇了。
3. 應(yīng)該怎么寫(xiě)
print_time 需要返回一個(gè)函數(shù),這樣賦值給 foo函數(shù)后,正確寫(xiě)法如下所示:
- import datetime
- import time
- def print_time(g):
- def f():
- print('開(kāi)始執(zhí)行時(shí)間')
- print(datetime.datetime.today())
- g()
- print('結(jié)束時(shí)間')
- print(datetime.datetime.today())
- return f
裝飾 foo:
- @print_time
- def foo():
- time.sleep(2)
- print('hello world')
調(diào)用 foo ,運(yùn)行結(jié)果如下:
- foo()
- 開(kāi)始執(zhí)行時(shí)間
- 2021-04-02 22:32:49.114124
- hello world
- 結(jié)束時(shí)間
- 2021-04-02 22:32:51.119506
一切正常
4. 裝飾器好處
上面自定義print_time裝飾器,除了能裝飾foo函數(shù)外,還能裝飾任意其他函數(shù)和類(lèi)內(nèi)方法。
裝飾任意一個(gè)函數(shù) foo2:
- @print_time
- def foo2():
- print('this is foo2')
裝飾類(lèi)內(nèi)方法 foo3,需要稍微修改原來(lái)的print_time:
- def print_time(g):
- def f(*args, **kargs):
- print('開(kāi)始執(zhí)行時(shí)間')
- print(datetime.datetime.today())
- g(*args, **kargs)
- print('結(jié)束時(shí)間')
- print(datetime.datetime.today())
- return f
為類(lèi)MyClass中foo3方法增加print_time裝飾:
- class MyClass(object):
- @print_time
- def foo3(self):
- print('this is a method of class')
執(zhí)行結(jié)果如下:
- MyClass().foo3()
- 開(kāi)始執(zhí)行時(shí)間
- 2021-04-02 23:16:32.094025
- this is a method of class
- 結(jié)束時(shí)間
- 2021-04-02 23:16:32.094078
以上就是裝飾器的通俗解釋?zhuān)綍r(shí)可以多用用,讓我們的代碼更加精煉、可讀。
名稱(chēng)欄目:這樣用裝飾器,為什么不行?
網(wǎng)站URL:http://fisionsoft.com.cn/article/djegsod.html


咨詢(xún)
建站咨詢(xún)
