Python借助with語句實現(xiàn)代碼段只執(zhí)行有限次
debug的時候,有時希望打印某些東西,但是如果代碼段剛好在一個循環(huán)或者是其他會被執(zhí)行很多次的部分,那么用來print的語句也會被執(zhí)行很多次,看起來就不美觀。
例如:
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) ''' 打印結果: <class 'int'> <class 'int'> <class 'int'> 3 '''
有3個 <class ‘int’>,很不好看。
為了解決這個問題,可以借助with語句實現(xiàn),首先要定義一個能夠在with語句中使用的類(實現(xiàn)了__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是標簽,相同標簽共用執(zhí)行次數(shù)計數(shù)器;limit是限制執(zhí)行的次數(shù)。例子如下:
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)打印結果:
<class 'int'>
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共用了計數(shù)器,因此總共只會執(zhí)行4次)
1 <class 'int'>
1 <class 'int'>
1 <class 'int'>
2 <class 'int'>
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不共用計數(shù)器)
1 <class 'int'>
1 <class 'int'>
1 <class 'int'>
2 <class 'int'>
2 <class 'int'>
2 <class 'int'>
6
到此這篇關于Python借助with語句實現(xiàn)代碼段只執(zhí)行有限次的文章就介紹到這了,更多相關Python代碼段執(zhí)行有限次內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Scrapy項目實戰(zhàn)之爬取某社區(qū)用戶詳情
這篇文章主要介紹了Scrapy項目實戰(zhàn)之爬取某社區(qū)用戶詳情,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-09-09
python+influxdb+shell編寫區(qū)域網(wǎng)絡狀況表
這篇文章主要為大家詳細介紹了python+influxdb+shell編寫區(qū)域網(wǎng)絡狀況表,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-07-07
Python實現(xiàn)隨機生成手機號及正則驗證手機號的方法
這篇文章主要介紹了Python實現(xiàn)隨機生成手機號及正則驗證手機號的方法,涉及Python基于random模塊的隨機數(shù)以及基于re模塊的正則驗證相關操作技巧,需要的朋友可以參考下2018-04-04
numpy和tensorflow中的各種乘法(點乘和矩陣乘)
這篇文章主要介紹了numpy和tensorflow中的各種乘法(點乘和矩陣乘),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-03-03

