詳解Python函數(shù)式編程之裝飾器
一、裝飾器的本質(zhì):
裝飾器(decorator)本質(zhì)是函數(shù)閉包(function closure)的語法糖(Syntactic sugar)
函數(shù)閉包(function closure):
函數(shù)閉包是函數(shù)式語言(函數(shù)是一等公民,可作為變量使用)中的術(shù)語。函數(shù)閉包:一個函數(shù),其參數(shù)和返回值都是函數(shù),用于增強(qiáng)函數(shù)功能,面向切面編程(AOP)
import time
# 控制臺打印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)計時間的功能:
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ì)上是一個函數(shù),閉包函數(shù)的傳入?yún)?shù)和返回值都是函數(shù),閉包函數(shù)得到返回值函數(shù)是對傳入函數(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())) # 起始時間
func() # 執(zhí)行函數(shù)
end_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) # 結(jié)束時間
print("Logging: func:{} runs from {} to {}".format(func.__name__, start_time, end_time))
return improved_func二、裝飾器使用方法:
通過裝飾器進(jìn)行函數(shù)增強(qiáng),只是一種語法糖,本質(zhì)上跟上個程序(使用函數(shù)閉包)完全一致。

import time
# 函數(shù)閉包:用于增強(qiáng)函數(shù)func:給函數(shù)func增加統(tǒng)計時間的功能:
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
# 控制臺打印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ù)添加裝飾器,等價于執(zhí)行了下面這條語句:
# print_odd = count_time_wrapper(print_odd)
print_odd()裝飾器在第一次調(diào)用被裝飾函數(shù)時進(jìn)行增強(qiáng),只增強(qiáng)一次,下次調(diào)用仍然是調(diào)用增強(qiáng)后的函數(shù),不會重復(fù)執(zhí)行增強(qiáng)!
保留函數(shù)參數(shù)和返回值的函數(shù)閉包:
- 之前所寫的函數(shù)閉包,在增強(qiáng)主要功能函數(shù)時,沒有保留原主要功能函數(shù)的參數(shù)列表和返回值。
- 一個保留參數(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)計時間的功能:
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
# 計算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"計算結(jié)果為{result}!")三、多個裝飾器的執(zhí)行順序:
# 裝飾器1:
def wrapper1(func1):
print("set func1") # 在wrapper1裝飾函數(shù)時輸出
def improved_func1(*args, **kwargs):
print("call func1") # 在wrapper1裝飾過的函數(shù)被調(diào)用時輸出
func1(*args, **kwargs)
return None
return improved_func1
# 裝飾器2:
def wrapper2(func2):
print("set func2") # 在wrapper2裝飾函數(shù)時輸出
def improved_func2(*args, **kwargs):
print("call func1") # 在wrapper2裝飾過的函數(shù)被調(diào)用時輸出
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í)行,原因是因為:程序從上往下執(zhí)行,當(dāng)運行到:
@wrapper1
@wrapper2
def original_func():
pass這段代碼時,使用函數(shù)閉包的方式解析為:
original_func = wrapper1(wrapper2(original_func))
所以先進(jìn)行wrapper2裝飾,然后再對被wrapper2裝飾完成的增強(qiáng)函數(shù)再由wrapper1進(jìn)行裝飾,返回最終的增強(qiáng)函數(shù)。

四、創(chuàng)建帶參數(shù)的裝飾器:
裝飾器允許傳入?yún)?shù),一個攜帶了參數(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")將其 @語法 去除,恢復(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é)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
educoder之Python數(shù)值計算庫Numpy圖像處理詳解
這篇文章主要為大家介紹了educoder之Python數(shù)值計算庫Numpy圖像處理詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
python+opencv+caffe+攝像頭做目標(biāo)檢測的實例代碼
今天小編就為大家分享一篇python+opencv+caffe+攝像頭做目標(biāo)檢測的實例代碼,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08
在Python中用GDAL實現(xiàn)矢量對柵格的切割實例
這篇文章主要介紹了在Python中用GDAL實現(xiàn)矢量對柵格的切割實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
python中使用 xlwt 操作excel的常見方法與問題
這篇文章主要給大家介紹了關(guān)于python中使用 xlwt 操作excel的常見方法與問題的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-01-01

