Python裝飾器的從入門到高階用法詳解!
首先要恭喜你,點進了這一篇十足乾貨。
不怕感動自己,這篇文章,小編足足整理了三天之久。絕對值得收藏,以備後用。
今天小明要講的是,Python中的裝飾器內容。
我會從裝飾器的入門用法逐步講到其高階用法
進群進群:700341555可以獲取Python各類入門學習資料!
這是我的微信公眾號【Python程式設計之家】各位大佬用空可以關注下,每天更新Python學習方法,感謝!
111111111111.png
image
目錄如下
- 裝飾器語法糖
- 入門用法:日誌列印器
- 入門用法:時間計時器
- 進階用法:帶引數的函式裝飾器
- 高階用法:不帶引數的類裝飾器
- 高階用法:帶引數的類裝飾器
- 內建裝飾器:property
- 其他裝飾器:裝飾器實戰
. 裝飾器語法糖
如果你接觸 Python 有一段時間了的話,想必你對 @ 符號一定不陌生了,沒錯 @ 符號就是裝飾器的語法糖。
它放在函式開始定義的地方,它就像一頂帽子一樣戴在函式的頭上。和這個函式繫結在一起。在我們呼叫這個函式的時候,第一件事並不是執行這個函式,而是將這個函式做為引數傳入它頭頂上這頂帽子,這頂帽子我們稱之為裝飾函式 或 裝飾器。
你要問我裝飾器可以實現什麼功能?這個真的是無解,小明只能說你的腦洞有多大,裝飾器就有多強大。
裝飾器的使用方法很固定:
- 先定義一個裝飾函式(帽子)
- 再定義你的業務函式(人)
- 最後把這頂帽子帶在這個人頭上
裝飾器的簡單的用法有很多,這裡舉兩個常見的。
- 日誌列印器
- 時間計時器
. 入門用法:日誌列印器
首先是日誌列印器。
實現的功能:
在函式執行前,先列印一行日誌告知一下主人,我要執行函數了。在函式執行完,也不能拍拍屁股就走人了,咱可是有禮貌的程式碼,再列印一行日誌告知下主人,我執行完啦。
<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">
# 這是裝飾函式
def logger(func):
def wrapper(*args, **kw):
print('我準備開始計算:{} 函數了:'.format(func.__name__))
# 真正執行的是這行。
func(*args, **kw)
print('啊哈,我計算完啦。給自己加個雞腿!!')
return wrapper
</pre>
假如,我的業務函式是,計算兩個數之和。寫好後,直接給它帶上帽子。
<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">
@logger
def add(x, y):
print('{} + {} = {}'.format(x, y, x+y))
</pre>
然後我們來計算一下。
<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">
add(200, 50)
</pre>
快來看看輸出了什麼,神奇不?
<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">
我準備開始計算:add 函數了:
200 + 50 = 250
啊哈,我計算完啦。給自己加個雞腿!
</pre>
. 入門用法:時間計時器
再來看看 時間計時器
實現功能:
顧名思義,就是計算一個函式的執行時長。
<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">
# 這是裝飾函式
def timer(func):
def wrapper(*args, **kw):
t1=time.time()
# 這是函式真正執行的地方
func(*args, **kw)
t2=time.time()
# 計算下時長
cost_time = t2-t1
print("花費時間:{}秒".format(cost_time))
return wrapper
</pre>
假如,我們的函式是要睡眠 2秒(冏~,小明實在不知道要舉什麼例子了)。這樣也能更好的看出這個計算時長到底靠不靠譜。
<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">
import time
@timer
def want_sleep(sleep_time):
time.sleep(sleep_time)
want_sleep( 2)
</pre>
來看看,輸出。真的是2秒耶。真歷害!!!
<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">
花費時間:2.0073800086975098秒
</pre>
. 進階用法:帶引數的函式裝飾器
通過上面簡單的入門,你大概已經感受到了裝飾的神奇魅力了。
不過,裝飾器的用法遠不止如此。我們今天就要把這個知識點講透。
上面的例子,裝飾器是不能接收引數的。其用法,只能適用於一些簡單的場景。不傳參的裝飾器,只能對被裝飾函式,執行固定邏輯。
如果你有經驗,你一定經常在專案中,看到有的裝飾器是帶有引數的。
裝飾器本身是一個函式,既然做為一個函式都不能攜帶函式,那這個函式的功能就很受限。只能執行固定的邏輯。這無疑是非常不合理的。而如果我們要用到兩個內容大體一致,只是某些地方不同的邏輯。不傳參的話,我們就要寫兩個裝飾器。小明覺得這不能忍。
那麼裝飾器如何實現傳參呢,會比較複雜,需要兩層巢狀。
同樣,我們也來舉個例子。
我們要在這兩個函式的執行的時候,分別根據其國籍,來說出一段打招呼的話。
<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">
def american():
print("我來自中國。")
def chinese():
print("I am from America.")
</pre>
在給他們倆戴上裝飾器的時候,就要跟裝飾器說,這個人是哪國人,然後裝飾器就會做出判斷,打出對應的招呼。
戴上帽子後,是這樣的。
<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">
@say_hello("china")
def american():
print("我來自中國。")
@say_hello("america")
def chinese():
print("I am from America.")
</pre>
萬事俱備,只差帽子了。來定義一下,這裡需要兩層巢狀。
<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">
def say_hello(contry):
def wrapper(func):
def deco(*args, **kwargs):
if contry == "china":
print("你好!")
elif contry == "america":
print('hello.')
else:
return
# 真正執行函式的地方
func(*args, **kwargs)
return deco
return wrapper
</pre>
執行一下
<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">
american()
print("------------")
chinese()
</pre>
看看輸出結果。
<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">
你好!
我來自中國。
------------
hello.
I am from America
</pre>
emmmm,這很NB。。。
. 高階用法:不帶引數的類裝飾器
以上都是基於函式實現的裝飾器,在閱讀別人程式碼時,還可以時常發現還有基於類實現的裝飾器。
基於類裝飾器的實現,必須實現 call 和 init兩個內建函式。
init :接收被裝飾函式
call :實現裝飾邏輯。
<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">
class logger(object):
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print("[INFO]: the function {func}() is running..."\
.format(func=self.func.__name__))
return self.func(*args, **kwargs)
@logger
def say(something):
print("say {}!".format(something))
say("hello")
</pre>
執行一下,看看輸出
<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">
[INFO]: the function say() is running...
say hello!
</pre>
. 高階用法:帶引數的類裝飾器
上面不帶引數的例子,你發現沒有,只能列印INFO級別的日誌,正常情況下,我們還需要列印DEBUG WARNING等級別的日誌。 這就需要給類裝飾器傳入引數,給這個函式指定級別了。
帶引數和不帶引數的類裝飾器有很大的不同。
init :不再接收被裝飾函式,而是接收傳入引數。
call :接收被裝飾函式,實現裝飾邏輯。
<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">
class logger(object):
def __init__(self, level='INFO'):
self.level = level
def __call__(self, func): # 接受函式
def wrapper(*args, **kwargs):
print("[{level}]: the function {func}() is running..."\
.format(level=self.level, func=func.__name__))
func(*args, **kwargs)
return wrapper #返回函式
@logger(level='WARNING')
def say(something):
print("say {}!".format(something))
say("hello")
</pre>
我們指定WARNING級別,執行一下,來看看輸出。
<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">
[WARNING]: the function say() is running...
say hello!
</pre>
. 內建裝飾器:property
以上,我們介紹的都是自定義的裝飾器。
其實Python語言本身也有一些裝飾器。比如property這個內建裝飾器,我們再熟悉不過了。
它通常存在於類中,可以將一個函式定義成一個屬性,屬性的值就是該函式return的內容。
通常我們給例項繫結屬性是這樣的
<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">
class Student(object):
def __init__(self, name, age=None):
self.name = name
self.age = age
# 例項化
XiaoMing = Student("小明")
# 新增屬性
XiaoMing.age=25
# 查詢屬性
XiaoMing.age
# 刪除屬性
del XiaoMing.age
</pre>
但是稍有經驗的開發人員,一下就可以看出,這樣直接把屬性暴露出去,雖然寫起來很簡單,但是並不能對屬性的值做合法性限制。為了實現這個功能,我們可以這樣寫。
<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">
class Student(object):
def __init__(self, name):
self.name = name
self.name = None
def set_age(self, age):
if not isinstance(age, int):
raise ValueError('輸入不合法:年齡必須為數值!')
if not 0 < age < 100:
raise ValueError('輸入不合法:年齡範圍必須0-100')
self._age=age
def get_age(self):
return self._age
def del_age(self):
self._age = None
XiaoMing = Student("小明")
# 新增屬性
XiaoMing.set_age(25)
# 查詢屬性
XiaoMing.get_age()
# 刪除屬性
XiaoMing.del_age()
</pre>
上面的程式碼設計雖然可以變數的定義,但是可以發現不管是獲取還是賦值(通過函式)都和我們平時見到的不一樣。
按照我們思維習慣應該是這樣的。
<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">
# 賦值
XiaoMing.age = 25
# 獲取
XiaoMing.age
</pre>
那麼這樣的方式我們如何實現呢。請看下面的程式碼。
<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">
class Student(object):
def __init__(self, name):
self.name = name
self.name = None
@property
def age(self):
return self._age
@age.setter
def age(self, value):
if not isinstance(value, int):
raise ValueError('輸入不合法:年齡必須為數值!')
if not 0 < value < 100:
raise ValueError('輸入不合法:年齡範圍必須0-100')
self._age=value
@age.deleter
def age(self):
del self._age
XiaoMing = Student("小明")
# 設定屬性
XiaoMing.age = 25
# 查詢屬性
XiaoMing.age
# 刪除屬性
del XiaoMing.age
</pre>
用@property裝飾過的函式,會將一個函式定義成一個屬性,屬性的值就是該函式return的內容。同時,會將這個函式變成另外一個裝飾器。就像後面我們使用的@age.setter和@age.deleter。
@age.setter 使得我們可以使用XiaoMing.age = 25這樣的方式直接賦值。
@age.deleter 使得我們可以使用del XiaoMing.age這樣的方式來刪除屬性。
. 其他裝飾器:裝飾器實戰
讀完並理解了上面的內容,你可以說是Python高手了。別懷疑,自信點,因為很多人都不知道裝飾器有這麼多用法呢。
在小明看來,使用裝飾器,可以達到如下目的:
- 使程式碼可讀性更高,逼格更高;
- 程式碼結構更加清晰,程式碼冗餘度更低;
剛好小明在最近也有一個場景,可以用裝飾器很好的實現,暫且放上來看看。
這是一個實現控制函式執行超時的裝飾器。如果超時,則會丟擲超時異常。
有興趣的可以看看。
<pre class="ql-align-justify" style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-weight: normal; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">
import signal
class TimeoutException(Exception):
def __init__(self, error='Timeout waiting for response from Cloud'):
Exception.__init__(self, error)
def timeout_limit(timeout_time):
def wraps(func):
def handler(signum, frame):
raise TimeoutException()
def deco(*args, **kwargs):
signal.signal(signal.SIGALRM, handler)
signal.alarm(timeout_time)
func(*args, **kwargs)
signal.alarm(0)
return deco
return wraps
</pre>