詳解Python函數(shù)式編程之裝飾器
一、裝飾器的本質(zhì):
裝飾器(decorator)本質(zhì)是函數(shù)閉包(function closure)的語(yǔ)法糖(Syntactic sugar)
函數(shù)閉包(function closure):
函數(shù)閉包是函數(shù)式語(yǔ)言(函數(shù)是一等公民,可作為變量使用)中的術(shù)語(yǔ)。函數(shù)閉包:一個(gè)函數(shù),其參數(shù)和返回值都是函數(shù),用于增強(qiáng)函數(shù)功能,面向切面編程(AOP)
import time
# 控制臺(tái)打印100以內(nèi)的奇數(shù):
def print_odd():
for i in range(100):
if i % 2 == 1:
print(i)
# 函數(shù)閉包:用于增強(qiáng)函數(shù)func:給函數(shù)func增加統(tǒng)計(jì)時(shí)間的功能:
def count_time_wrapper(func):
def improved_func():
start_time = time.time()
func()
end_time = time.time()
print(f"It takes {end_time - start_time} S to find all the odds in range !!!")
return improved_func
if __name__ == '__main__':
# 調(diào)用count_time_wrapper增強(qiáng)函數(shù)
print_odd = count_time_wrapper(print_odd)
print_odd()閉包本質(zhì)上是一個(gè)函數(shù),閉包函數(shù)的傳入?yún)?shù)和返回值都是函數(shù),閉包函數(shù)得到返回值函數(shù)是對(duì)傳入函數(shù)增強(qiáng)后的結(jié)果。
日志裝飾器:
def log_wrapper(func):
"""
閉包,用于增強(qiáng)函數(shù)func: 給func增加日志功能
"""
def improved_func():
start_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) # 起始時(shí)間
func() # 執(zhí)行函數(shù)
end_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) # 結(jié)束時(shí)間
print("Logging: func:{} runs from {} to {}".format(func.__name__, start_time, end_time))
return improved_func二、裝飾器使用方法:
通過(guò)裝飾器進(jìn)行函數(shù)增強(qiáng),只是一種語(yǔ)法糖,本質(zhì)上跟上個(gè)程序(使用函數(shù)閉包)完全一致。

import time
# 函數(shù)閉包:用于增強(qiáng)函數(shù)func:給函數(shù)func增加統(tǒng)計(jì)時(shí)間的功能:
def count_time_wrapper(func):
def improved_func():
start_time = time.time()
func()
end_time = time.time()
print(f"It takes {end_time - start_time} S to find all the odds in range !!!")
return improved_func
# 控制臺(tái)打印100以內(nèi)的奇數(shù):
@count_time_wrapper # 添加裝飾器
def print_odd():
for i in range(100):
if i % 2 == 1:
print(i)
if __name__ == '__main__':
# 使用 @裝飾器(增強(qiáng)函數(shù)名) 給當(dāng)前函數(shù)添加裝飾器,等價(jià)于執(zhí)行了下面這條語(yǔ)句:
# print_odd = count_time_wrapper(print_odd)
print_odd()裝飾器在第一次調(diào)用被裝飾函數(shù)時(shí)進(jìn)行增強(qiáng),只增強(qiáng)一次,下次調(diào)用仍然是調(diào)用增強(qiáng)后的函數(shù),不會(huì)重復(fù)執(zhí)行增強(qiáng)!
保留函數(shù)參數(shù)和返回值的函數(shù)閉包:
- 之前所寫的函數(shù)閉包,在增強(qiáng)主要功能函數(shù)時(shí),沒有保留原主要功能函數(shù)的參數(shù)列表和返回值。
- 一個(gè)保留參數(shù)列表和返回值的函數(shù)閉包寫法:
def general_wrapper(func):
def improved_func(*args, **kwargs):
# 增強(qiáng)函數(shù)功能:
ret = func(*args, **kwargs)
# 增強(qiáng)函數(shù)功能:
return ret
return improved_func優(yōu)化裝飾器(參數(shù)傳遞、設(shè)置返回值):
import time
# 函數(shù)閉包:用于增強(qiáng)函數(shù)func:給函數(shù)func增加統(tǒng)計(jì)時(shí)間的功能:
def count_time_wrapper(func):
# 增強(qiáng)函數(shù):
def improved_func(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"It takes {end_time - start_time} S to find all the odds in range !!!")
# 原函數(shù)返回值
return result
return improved_func
# 計(jì)算0-lim奇數(shù)之和:
@count_time_wrapper
def count_odds(lim):
cnt = 0
for i in range(lim):
if i % 2 == 1:
cnt = cnt + i
return cnt
if __name__ == '__main__':
result = count_odds(10000000)
print(f"計(jì)算結(jié)果為{result}!")三、多個(gè)裝飾器的執(zhí)行順序:
# 裝飾器1:
def wrapper1(func1):
print("set func1") # 在wrapper1裝飾函數(shù)時(shí)輸出
def improved_func1(*args, **kwargs):
print("call func1") # 在wrapper1裝飾過(guò)的函數(shù)被調(diào)用時(shí)輸出
func1(*args, **kwargs)
return None
return improved_func1
# 裝飾器2:
def wrapper2(func2):
print("set func2") # 在wrapper2裝飾函數(shù)時(shí)輸出
def improved_func2(*args, **kwargs):
print("call func1") # 在wrapper2裝飾過(guò)的函數(shù)被調(diào)用時(shí)輸出
func2(*args, **kwargs)
return None
return improved_func2
@wrapper1
@wrapper2
def original_func():
pass
if __name__ == '__main__':
original_func()
print("------------")
original_func()
這里得到的執(zhí)行結(jié)果是,wrapper2裝飾器先執(zhí)行,原因是因?yàn)椋撼绦驈纳贤聢?zhí)行,當(dāng)運(yùn)行到:
@wrapper1
@wrapper2
def original_func():
pass這段代碼時(shí),使用函數(shù)閉包的方式解析為:
original_func = wrapper1(wrapper2(original_func))
所以先進(jìn)行wrapper2裝飾,然后再對(duì)被wrapper2裝飾完成的增強(qiáng)函數(shù)再由wrapper1進(jìn)行裝飾,返回最終的增強(qiáng)函數(shù)。

四、創(chuàng)建帶參數(shù)的裝飾器:
裝飾器允許傳入?yún)?shù),一個(gè)攜帶了參數(shù)的裝飾器將有三層函數(shù),如下所示:
import functools
def log_with_param(text):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print('call %s():' % func.__name__)
print('args = {}'.format(*args))
print('log_param = {}'.format(text))
return func(*args, **kwargs)
return wrapper
return decorator
@log_with_param("param!!!")
def test_with_param(p):
print(test_with_param.__name__)
if __name__ == '__main__':
test_with_param("test")將其 @語(yǔ)法 去除,恢復(fù)函數(shù)調(diào)用的形式:
# 傳入裝飾器的參數(shù),并接收返回的decorator函數(shù)
decorator = log_with_param("param!!!")
# 傳入test_with_param函數(shù)
wrapper = decorator(test_with_param)
# 調(diào)用裝飾器函數(shù)
wrapper("I'm a param")總結(jié)
本篇文章就到這里了,希望能夠給你帶來(lái)幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
Python光學(xué)仿真教程實(shí)現(xiàn)光線追蹤
傳統(tǒng)的高斯光學(xué)是建立在傍軸近似基礎(chǔ)之上的理想成像理論,這種處理以物像關(guān)系為核心,通過(guò)基點(diǎn)對(duì)光路的成像特性進(jìn)行描述。然而,傍軸近似在一定程度上犧牲了精確性,從而使得需要一套像差理論作為補(bǔ)充2021-10-10
利用Python實(shí)現(xiàn)命令行版的火車票查看器
當(dāng)你想查詢一下火車票信息的時(shí)候,你還在上12306官網(wǎng)嗎?或是打開你手機(jī)里的APP?下面讓我們來(lái)用Python寫一個(gè)命令行版的火車票查看器, 只要在命令行敲一行命令就能獲得你想要的火車票信息!如果你剛掌握了Python基礎(chǔ),這將是個(gè)不錯(cuò)的小練習(xí)。2016-08-08
django rest framework使用django-filter用法
這篇文章主要介紹了django rest framework使用django-filter用法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-07-07
python內(nèi)置函數(shù)delattr()與dict()舉例詳解
這篇文章主要介紹了關(guān)于python內(nèi)置函數(shù)delattr()與dict()的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08
python實(shí)現(xiàn)PyEMD經(jīng)驗(yàn)?zāi)B(tài)分解殘差量分析
這篇文章主要為大家介紹了PyEMD經(jīng)驗(yàn)?zāi)B(tài)分解及變體殘余量分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05

