Python借助with语句实现代码段只执行有限次
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) ''' 打印结果: <class 'int'> <class 'int'> <class 'int'> 3 '''
有3个 <class ‘int’>,很不好看。
为了解决这个问题,可以借助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)打印结果:
<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共用了计数器,因此总共只会执行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不共用计数器)
1 <class 'int'>
1 <class 'int'>
1 <class 'int'>
2 <class 'int'>
2 <class 'int'>
2 <class 'int'>
6
到此这篇关于Python借助with语句实现代码段只执行有限次的文章就介绍到这了,更多相关Python代码段执行有限次内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
python 按照sheet合并多个Excel的示例代码(多个sheet)
这篇文章主要介绍了python 按照sheet合并多个Excel的示例代码(多个sheet),本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2021-09-09
Python+opencv+pyaudio实现带声音屏幕录制
今天小编就为大家分享一篇Python+opencv+pyaudio实现带声音屏幕录制,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2019-12-12
在Python中append以及extend返回None的例子
今天小编就为大家分享一篇在Python中append以及extend返回None的例子,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2019-07-07
如何实现在jupyter notebook中播放视频(不停地展示图片)
这篇文章主要介绍了如何实现在jupyter notebook中播放视频(不停地展示图片),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-04-04


最新评论