通俗講解python 裝飾器
裝飾器其實(shí)一直是我的一個(gè)"老大難"。這個(gè)知識(shí)點(diǎn)就放在那,但是拖延癥。。。
其實(shí)在平常寫寫腳本的過程中,這個(gè)知識(shí)點(diǎn)你可能用到不多
但在面試的時(shí)候,這可是一個(gè)高頻問題。
一、什么是裝飾器
所謂的裝飾器,其實(shí)就是通過裝飾器函數(shù),來修改原函數(shù)的一些功能,使得原函數(shù)不需要修改。
這一句話理解起來可能沒那么輕松,那先來看一個(gè)"傻瓜"函數(shù)。
放心,絕對(duì)不是"Hello World"!
def hello():
print("你好,裝飾器")
腫么樣,木騙你吧? 哈哈,這個(gè)函數(shù)不用運(yùn)行相信大家都知道輸出結(jié)果:"你好,裝飾器"。
那如果我想讓hello()函數(shù)再實(shí)現(xiàn)個(gè)其他功能,比如多打印一句話。
那么,可以這樣"增強(qiáng)"一下:
def my_decorator(func):
def wrapper():
print("這是裝飾后具有的新輸出")
func()
return wrapper
def hello():
print("你好,裝飾器")
hello = my_decorator(hello)
hello()
運(yùn)行結(jié)果:
這是裝飾后具有的新輸出
你好,裝飾器
[Finished in 0.1s]
很顯然,這個(gè)"增強(qiáng)"沒啥作用,但是可以幫助理解裝飾器。
當(dāng)運(yùn)行最后的hello()函數(shù)時(shí),調(diào)用過程是這樣的:
hello = my_decorator(hello)中,變量hello指向的是my_decorator()my_decorator(func)中傳參是hello,返回的wrapper,因此又會(huì)調(diào)用到原函數(shù)hello()- 于是乎,先打印出了
wrapper()函數(shù)里的,然后才打印出hello()函數(shù)里的
那上述代碼里的my_decorator()就是一個(gè)裝飾器。
它改變了hello()的行為,但是并沒有去真正的改變hello()函數(shù)的內(nèi)部實(shí)現(xiàn)。
但是,python一直以"優(yōu)雅"被人追捧,而上述的代碼顯然不夠優(yōu)雅。
二、優(yōu)雅的裝飾器
所以,想讓上述裝飾器變得優(yōu)雅,可以這樣寫:
def my_decorator(func):
def wrapper():
print("這是裝飾后具有的新輸出")
func()
return wrapper
@my_decorator
def hello():
print("你好,裝飾器")
hello()
這里的@my_decorator就相當(dāng)于舊代碼的hello = my_decorator(hello),@符號(hào)稱為語法糖。
那如果還有其他函數(shù)也需要加上類似的裝飾,直接在函數(shù)的上方加上@my_decorator就可以,大大提高函數(shù)
的重復(fù)利用與可讀性。
def my_decorator(func):
def wrapper():
print("這是裝飾后具有的新輸出")
func()
return wrapper
@my_decorator
def hello():
print("你好,裝飾器")
@my_decorator
def hello2():
print("你好,裝飾器2")
hello2()
輸出:
這是裝飾后具有的新輸出
你好,裝飾器2
[Finished in 0.1s]
三、帶參數(shù)的裝飾器
1. 單個(gè)參數(shù)
上面的只是一個(gè)非常簡(jiǎn)單的裝飾器,但是實(shí)際場(chǎng)景中,很多函數(shù)都是要帶有參數(shù)的,比如hello(people_name)。
其實(shí)也很簡(jiǎn)單,要什么我們就給什么唄,直接在對(duì)應(yīng)裝飾器的wrapper()上,加上對(duì)應(yīng)的參數(shù):
def my_decorator(func):
def wrapper(people_name):
print("這是裝飾后具有的新輸出")
func(people_name)
return wrapper
@my_decorator
def hello(people_name):
print("你好,{}".format(people_name))
hello("張三")
輸出:
這是裝飾后具有的新輸出
你好,張三
[Finished in 0.1s]
2. 多個(gè)參數(shù)
但是還沒完,這樣雖然簡(jiǎn)單,但是隨之而來另一個(gè)問題:因?yàn)椴⒉皇撬泻瘮?shù)參數(shù)都是一樣的,
當(dāng)其他要使用裝飾器的函數(shù)參數(shù)不止這個(gè)一個(gè)腫么辦?比如:
@my_decorator
def hello3(speaker, listener):
print("{}對(duì){}說你好!".format(speaker, listener))
沒關(guān)系,在python里,*args和**kwargs表示接受任意數(shù)量和類型的參數(shù),所以我們可以這樣
寫裝飾器里的wrapper()函數(shù):
def my_decorator(func):
def wrapper(*args, **kwargs):
print("這是裝飾后具有的新輸出")
func(*args, **kwargs)
return wrapper
@my_decorator
def hello(people_name):
print("你好,{}".format(people_name))
@my_decorator
def hello3(speaker, listener):
print("{}對(duì){}說你好!".format(speaker, listener))
hello("老王")
print("------------------------")
hello3("張三", "李四")
同時(shí)運(yùn)行下hello("老王"),和hello3("張三", "李四"),看結(jié)果:
這是裝飾后具有的新輸出
你好,老王
------------------------
這是裝飾后具有的新輸出
張三對(duì)李四說你好!
[Finished in 0.1s]
3. 自定義參數(shù)
上面2種,裝飾器都是接收外來的參數(shù),其實(shí)裝飾器還可以接收自己的參數(shù)。
比如,我加個(gè)參數(shù)來控制下裝飾器中打印信息的次數(shù):
def count(num):
def my_decorator(func):
def wrapper(*args, **kwargs):
for i in range(num):
print("這是裝飾后具有的新輸出")
func(*args, **kwargs)
return wrapper
return my_decorator
@count(3)
def hello(people_name):
print("你好,{}".format(people_name))
hello("老王")
注意,這里count裝飾函數(shù)中的2個(gè)return.
運(yùn)行下,應(yīng)該會(huì)出現(xiàn)3次:
這是裝飾后具有的新輸出
你好,老王
這是裝飾后具有的新輸出
你好,老王
這是裝飾后具有的新輸出
你好,老王
[Finished in 0.1s]
4. 內(nèi)置裝飾器@functools.wrap
現(xiàn)在多做一步探索,我們來打印下下面例子中的hello()函數(shù)的元信息:
def my_decorator(func):
def wrapper(*args, **kwargs):
print("這是裝飾后具有的新輸出")
func(*args, **kwargs)
return wrapper
@my_decorator
def hello(people_name):
print("你好,{}".format(people_name))
print(hello.__name__) #看下hello函數(shù)的元信息
輸出:
wrapper
這說明了,它不再是以前的那個(gè) hello() 函數(shù),而是被 wrapper() 函數(shù)取代了。
如果我們需要用到元函數(shù)信息,那怎么保留它呢?這時(shí)候可以用內(nèi)置裝飾器@functools.wrap。
import functools
def my_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print("這是裝飾后具有的新輸出")
func(*args, **kwargs)
return wrapper
@my_decorator
def hello(people_name):
print("你好,{}".format(people_name))
print(hello.__name__)
運(yùn)行下:
hello
[Finished in 0.1s]
四、類裝飾器
裝飾器除了是函數(shù)之外,也可以是類。
但是類作為裝飾器的話,需要依賴一個(gè)函數(shù)__call__(),當(dāng)調(diào)用這個(gè)類的實(shí)例時(shí),函數(shù)__call__()就
會(huì)被執(zhí)行。
來改造下之前的例子,把函數(shù)裝飾器改成類裝飾器:
class MyDecorator():
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print("這是裝飾后具有的新輸出")
return self.func(*args, **kwargs)
# def my_decorator(func):
# def wrapper():
# print("這是裝飾后具有的新輸出")
# func()
# return wrapper
@MyDecorator
def hello():
print("你好,裝飾器")
hello()
運(yùn)行:
這是裝飾后具有的新輸出
你好,裝飾器
[Finished in 0.1s]
跟函數(shù)裝飾器一樣,實(shí)現(xiàn)一樣的功能。
五、裝飾器的嵌套
既然裝飾器可以增強(qiáng)函數(shù)的功能,那如果有多個(gè)裝飾器,我都想要怎么辦?
其實(shí),只要把需要用的裝飾器都加上去就好了:
@decorator1 @decorator2 @decorator3 def hello(): ...
但是要注意這里的執(zhí)行順序,會(huì)從上到下去執(zhí)行,可以來看下:
def my_decorator(func):
def wrapper():
print("這是裝飾后具有的新輸出")
func()
return wrapper
def my_decorator2(func):
def wrapper():
print("這是裝飾后具有的新輸出2")
func()
return wrapper
def my_decorator3(func):
def wrapper():
print("這是裝飾后具有的新輸出3")
func()
return wrapper
@my_decorator
@my_decorator2
@my_decorator3
def hello():
print("你好,裝飾器")
hello()
運(yùn)行
這是裝飾后具有的新輸出
這是裝飾后具有的新輸出2
這是裝飾后具有的新輸出3
你好,裝飾器
[Finished in 0.1s]
好記性不如爛筆頭,寫一下理解一下會(huì)好很多。
以上就是通俗講解python 裝飾器的詳細(xì)內(nèi)容,更多關(guān)于python 裝飾器的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python機(jī)器學(xué)習(xí)庫scikit-learn入門開發(fā)示例
scikit-learn是一個(gè)開源Python語言機(jī)器學(xué)習(xí)工具包,它涵蓋了幾乎所有主流機(jī)器學(xué)習(xí)算法的實(shí)現(xiàn),并且提供了一致的調(diào)用接口。它基于Numpy和scipy等Python數(shù)值計(jì)算庫,提供了高效的算法實(shí)現(xiàn)2022-07-07
Pytorch實(shí)現(xiàn)的手寫數(shù)字mnist識(shí)別功能完整示例
這篇文章主要介紹了Pytorch實(shí)現(xiàn)的手寫數(shù)字mnist識(shí)別功能,結(jié)合完整實(shí)例形式分析了Pytorch模塊手寫字識(shí)別具體步驟與相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2019-12-12
python調(diào)用文件時(shí)找不到相對(duì)路徑的解決方案
這篇文章主要介紹了python調(diào)用文件時(shí)找不到相對(duì)路徑的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03
PyCharm 解決找不到新打開項(xiàng)目的窗口問題
這篇文章主要介紹了PyCharm 解決找不到新打開項(xiàng)目的窗口問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-01-01
Python?Asyncio?庫之同步原語常用函數(shù)詳解
這篇文章主要為大家介紹了Python?Asyncio?庫之同步原語常用函數(shù)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03
使用Python自動(dòng)化Microsoft Excel和Word的操作方法

