Python借助with语句实现代码段只执行有限次


Posted in Python onMarch 23, 2022

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 相关文章推荐
常用python数据类型转换函数总结
Mar 11 Python
Python中unittest用法实例
Sep 25 Python
python使用Plotly绘图工具绘制水平条形图
Mar 25 Python
pycharm创建一个python包方法图解
Apr 10 Python
用python写测试数据文件过程解析
Sep 25 Python
Python大数据之网络爬虫的post请求、get请求区别实例分析
Nov 16 Python
Python的几种主动结束程序方式
Nov 22 Python
python中的数组赋值与拷贝的区别详解
Nov 26 Python
python编写俄罗斯方块
Mar 13 Python
python 串行执行和并行执行实例
Apr 30 Python
Python pytesseract验证码识别库用法解析
Jun 29 Python
python OpenCV学习笔记
Mar 31 Python
python3 字符串str和bytes相互转换
Mar 23 #Python
对象析构函数__del__在Python中何时使用
详解Python内置模块Collections
Mar 22 #Python
Python中 range | np.arange | np.linspace三者的区别
Python中非常使用的6种基本变量的操作与技巧
python使用torch随机初始化参数
Mar 22 #Python
Django基础CBV装饰器和中间件
You might like
php图片加中文水印实现代码分享
2012/10/31 PHP
使用ThinkPHP的自动完成实现无限级分类实例详解
2016/09/02 PHP
PHP二维索引数组的遍历实例分析【2种方式】
2019/06/24 PHP
使用原生javascript创建通用表单验证——更锋利的使用dom对象
2011/09/13 Javascript
JQuery页面的表格数据的增加与分页的实现
2013/12/10 Javascript
利用a标签自动解析URL分析网址实例
2014/10/20 Javascript
Javascript前端UI框架Kit使用指南之Kitjs简介
2014/11/28 Javascript
JavaScript中的变量作用域介绍
2014/12/31 Javascript
Underscore.js常用方法总结
2015/02/28 Javascript
JavaScript模拟实现继承的方法
2015/03/30 Javascript
JS实现支持多选的遍历下拉列表代码
2015/08/20 Javascript
JS如何判断是否为ie浏览器的方法(包括IE10、IE11在内)
2015/12/13 Javascript
JS基于MSClass和setInterval实现ajax定时采集信息并滚动显示的方法
2016/04/18 Javascript
Javascript之Number对象介绍
2016/06/07 Javascript
解决vue侦听器watch,调用this时出现undefined的问题
2020/10/30 Javascript
[01:15:12]DOTA2上海特级锦标赛主赛事日 - 1 败者组第一轮#4Newbee VS CDEC
2016/03/03 DOTA
浅析Python中的赋值和深浅拷贝
2017/08/15 Python
浅谈python中字典append 到list 后值的改变问题
2018/05/04 Python
Selenium鼠标与键盘事件常用操作方法示例
2018/08/13 Python
对numpy中二进制格式的数据存储与读取方法详解
2018/11/01 Python
Python 文本文件内容批量抽取实例
2018/12/10 Python
安装PyInstaller失败问题解决
2019/12/14 Python
PyTorch 解决Dataset和Dataloader遇到的问题
2020/01/08 Python
TensorFlow使用Graph的基本操作的实现
2020/04/22 Python
Python爬取微信小程序通用方法代码实例详解
2020/09/29 Python
社团活动策划书范文
2014/01/09 职场文书
数控技术应用个人求职信范文
2014/02/03 职场文书
酒店管理失职检讨书
2014/09/16 职场文书
大学生职业生涯十年规划书范文
2014/09/17 职场文书
单位作风建设自查报告
2014/10/23 职场文书
结婚通知短信大全
2015/04/17 职场文书
2015大学迎新晚会策划书
2015/07/16 职场文书
为什么不建议在go项目中使用init()
2021/04/12 Golang
Python 中random 库的详细使用
2021/06/03 Python
springboot临时文件存储目录配置方式
2021/07/01 Java/Android
《吸血鬼:避世 血猎》官宣4.27发售 系列首款大逃杀
2022/04/03 其他游戏