日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python借助with語句實現代碼段只執行有限次_python

作者:SDFDSJFJ ? 更新時間: 2022-05-26 編程語言

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

欄目分類
最近更新