網站首頁 編程語言 正文
debug的時候,有時希望打印某些東西,但是如果代碼段剛好在一個循環或者是其他會被執行很多次的部分,那么用來print的語句也會被執行很多次,看起來就不美觀。
例如:
a = 0 for i in range(3): ? ? a += 1 print(a)
這里在中間希望確認一下a的類型,debug的時候改成:
a = 0 for i in range(3): ? ? print(type(a)) ? ? a += 1 print(a) ''' 打印結果:3 '''
有3個
為了解決這個問題,可以借助with
語句實現,首先要定義一個能夠在with語句中使用的類(實現了__enter__和__exit__):
from typing import Any class LimitedRun(object): ? ? run_dict = {} ? ? def __init__(self, ? ? ? ? ? ? ? ? ?tag: Any = 'default', ? ? ? ? ? ? ? ? ?limit: int = 1): ? ? ? ? self.tag = tag ? ? ? ? self.limit = limit ? ? def __enter__(self): ? ? ? ? if self.tag in LimitedRun.run_dict.keys(): ? ? ? ? ? ? LimitedRun.run_dict[self.tag] += 1 ? ? ? ? else: ? ? ? ? ? ? LimitedRun.run_dict[self.tag] = 1 ? ? ? ? return LimitedRun.run_dict[self.tag] <= self.limit ? ? def __exit__(self, exc_type, exc_value, traceback): ? ? ? ? return tag是標簽,相同標簽共用執行次數計數器;limit是限制執行的次數。例子如下: a = 0 for i in range(3): ? ? with LimitedRun('print_1', 1) as limited_run: ? ? ? ? if limited_run: ? ? ? ? ? ? print(type(a)) ? ? a += 1 print(a)
打印結果:
3
a = 0 for i in range(3): ? ? with LimitedRun('print_1', 4) as limited_run: ? ? ? ? if limited_run: ? ? ? ? ? ? print(1, type(a)) ? ? a += 1 for i in range(3): ? ? with LimitedRun('print_1', 4) as limited_run: ? ? ? ? if limited_run: ? ? ? ? ? ? print(2, type(a)) ? ? a += 1 print(a)
?打印結果:(相同tag共用了計數器,因此總共只會執行4次)
1
1
1
2
6
a = 0 for i in range(3): ? ? with LimitedRun('print_1', 4) as limited_run: ? ? ? ? if limited_run: ? ? ? ? ? ? print(1, type(a)) ? ? a += 1 for i in range(3): ? ? with LimitedRun('print_2', 4) as limited_run: ? ? ? ? if limited_run: ? ? ? ? ? ? print(2, type(a)) ? ? a += 1 print(a)
打印結果:(不同tag不共用計數器)
1
1
1
2
2
2
6
原文鏈接:https://blog.csdn.net/qq_44980390/article/details/123673310
相關推薦
- 2022-09-14 C#實現自由組合本地緩存、分布式緩存和數據查詢_C#教程
- 2022-04-03 Go語言讀取txt文檔的操作方法_Golang
- 2022-12-08 React源碼state計算流程和優先級實例解析_React
- 2022-07-06 R語言繪制條形圖及分布密度圖代碼總結_python
- 2022-07-20 python計算機視覺實現全景圖像拼接示例_python
- 2022-10-08 ASP.NET堆和棧四之對托管和非托管資源的垃圾回收和內存分配_實用技巧
- 2022-09-16 Python封裝zabbix-get接口的代碼分享_python
- 2022-10-31 Kotlin協程開發之Flow的融合與Channel容量及溢出策略介紹_Android
- 最近更新
-
- 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同步修改后的遠程分支