網站首頁 編程語言 正文
一、裝飾器的本質:
裝飾器(decorator)本質是函數閉包(function closure)的語法糖(Syntactic sugar)
函數閉包(function closure):
函數閉包是函數式語言(函數是一等公民,可作為變量使用)中的術語。函數閉包:一個函數,其參數和返回值都是函數,用于增強函數功能,面向切面編程(AOP)
import time # 控制臺打印100以內的奇數: def print_odd(): for i in range(100): if i % 2 == 1: print(i) # 函數閉包:用于增強函數func:給函數func增加統計時間的功能: 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__': # 調用count_time_wrapper增強函數 print_odd = count_time_wrapper(print_odd) print_odd()
閉包本質上是一個函數,閉包函數的傳入參數和返回值都是函數,閉包函數得到返回值函數是對傳入函數增強后的結果。
日志裝飾器:
def log_wrapper(func): """ 閉包,用于增強函數func: 給func增加日志功能 """ def improved_func(): start_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) # 起始時間 func() # 執行函數 end_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) # 結束時間 print("Logging: func:{} runs from {} to {}".format(func.__name__, start_time, end_time)) return improved_func
二、裝飾器使用方法:
通過裝飾器進行函數增強,只是一種語法糖,本質上跟上個程序(使用函數閉包)完全一致。
import time # 函數閉包:用于增強函數func:給函數func增加統計時間的功能: 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以內的奇數: @count_time_wrapper # 添加裝飾器 def print_odd(): for i in range(100): if i % 2 == 1: print(i) if __name__ == '__main__': # 使用 @裝飾器(增強函數名) 給當前函數添加裝飾器,等價于執行了下面這條語句: # print_odd = count_time_wrapper(print_odd) print_odd()
裝飾器在第一次調用被裝飾函數時進行增強,只增強一次,下次調用仍然是調用增強后的函數,不會重復執行增強!
保留函數參數和返回值的函數閉包:
- 之前所寫的函數閉包,在增強主要功能函數時,沒有保留原主要功能函數的參數列表和返回值。
- 一個保留參數列表和返回值的函數閉包寫法:
def general_wrapper(func): def improved_func(*args, **kwargs): # 增強函數功能: ret = func(*args, **kwargs) # 增強函數功能: return ret return improved_func
優化裝飾器(參數傳遞、設置返回值):?
import time # 函數閉包:用于增強函數func:給函數func增加統計時間的功能: def count_time_wrapper(func): # 增強函數: 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 !!!") # 原函數返回值 return result return improved_func # 計算0-lim奇數之和: @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"計算結果為{result}!")
三、多個裝飾器的執行順序:
# 裝飾器1: def wrapper1(func1): print("set func1") # 在wrapper1裝飾函數時輸出 def improved_func1(*args, **kwargs): print("call func1") # 在wrapper1裝飾過的函數被調用時輸出 func1(*args, **kwargs) return None return improved_func1 # 裝飾器2: def wrapper2(func2): print("set func2") # 在wrapper2裝飾函數時輸出 def improved_func2(*args, **kwargs): print("call func1") # 在wrapper2裝飾過的函數被調用時輸出 func2(*args, **kwargs) return None return improved_func2 @wrapper1 @wrapper2 def original_func(): pass if __name__ == '__main__': original_func() print("------------") original_func()
這里得到的執行結果是,wrapper2裝飾器先執行,原因是因為:程序從上往下執行,當運行到:
@wrapper1 @wrapper2 def original_func(): pass
這段代碼時,使用函數閉包的方式解析為:
original_func = wrapper1(wrapper2(original_func))
所以先進行wrapper2裝飾,然后再對被wrapper2裝飾完成的增強函數再由wrapper1進行裝飾,返回最終的增強函數。
四、創建帶參數的裝飾器:
裝飾器允許傳入參數,一個攜帶了參數的裝飾器將有三層函數,如下所示:
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")
將其?@
語法?去除,恢復函數調用的形式:
# 傳入裝飾器的參數,并接收返回的decorator函數 decorator = log_with_param("param!!!") # 傳入test_with_param函數 wrapper = decorator(test_with_param) # 調用裝飾器函數 wrapper("I'm a param")
總結
原文鏈接:https://blog.csdn.net/weixin_52058417/article/details/123203323
相關推薦
- 2022-10-12 Docker安裝RabbitMQ的超詳細步驟_docker
- 2022-11-05 Nginx反向代理location和proxy_pass配置規則詳細總結_nginx
- 2022-04-07 對WPF中Expander控件美化_實用技巧
- 2022-04-03 Pandas搭配lambda組合使用詳解_python
- 2024-04-06 jeecg-boot使用QueryGenerator.initQueryWrapper怎么排序查詢
- 2022-10-07 Android調用系統圖庫獲取圖片的方法_Android
- 2022-01-18 獲取當前的日期 格式為YYYY-MM-dd 和時間戳轉時間
- 2022-12-14 C#中委托和事件的區別詳解_C#教程
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支