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编程中三条常用的技巧
May 11 Python
Python使用CMD模块更优雅的运行脚本
May 11 Python
浅谈python类属性的访问、设置和删除方法
Jul 25 Python
python3+PyQt5重新实现自定义数据拖放处理
Apr 19 Python
python 读取鼠标点击坐标的实例
Dec 29 Python
linux安装python修改默认python版本方法
Mar 31 Python
python图像处理入门(一)
Apr 04 Python
python绘图模块matplotlib示例详解
Jul 26 Python
python+django+rest框架配置创建方法
Aug 31 Python
django数据模型(Model)的字段类型解析
Dec 25 Python
Python中求对数方法总结
Mar 10 Python
使用keras内置的模型进行图片预测实例
Jun 17 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与MySQL开发中页面出现乱码的一种解决方法
2007/07/29 PHP
Laravel 连接(Join)示例
2019/10/16 PHP
ThinkPHP5 框架引入 Go AOP,PHP AOP编程项目详解
2020/05/12 PHP
jQuery1.3.2 升级到jQuery1.4.4需要修改的地方
2011/01/06 Javascript
jQuery使用之设置元素样式用法实例
2015/01/19 Javascript
JS实现兼容性好,自动置顶的淘宝悬浮工具栏效果
2015/09/18 Javascript
JavaScript实现带缓冲效果的随屏滚动漂浮广告代码
2015/11/06 Javascript
js拖拽的原型声明和用法总结
2016/04/04 Javascript
jQuery轻松实现表格的隔行变色和点击行变色的实例代码
2016/05/09 Javascript
JS自动生成动态HTML验证码页面
2017/06/14 Javascript
webpack之devtool详解
2018/02/10 Javascript
Django中对通过测试的用户进行限制访问的方法
2015/07/23 Python
Python文件读写保存操作的示例代码
2018/09/14 Python
python3.5安装python3-tk详解
2019/04/26 Python
python原类、类的创建过程与方法详解
2019/07/19 Python
安装python及pycharm的教程图解
2019/10/10 Python
pycharm中导入模块错误时提示Try to run this command from the system terminal
2020/03/26 Python
python 代码运行时间获取方式详解
2020/09/18 Python
全网最细 Python 格式化输出用法讲解(推荐)
2021/01/18 Python
python Protobuf定义消息类型知识点讲解
2021/03/02 Python
英国马莎百货官网:Marks & Spencer
2016/07/29 全球购物
如何利用XMLHTTP检测URL及探测服务器信息
2013/11/10 面试题
公司业务主管岗位职责
2013/12/07 职场文书
高中生操行评语
2014/04/25 职场文书
工商管理自荐书
2014/07/06 职场文书
励志演讲稿800字
2014/08/21 职场文书
普通党员对照检查材料
2014/08/28 职场文书
2014年人力资源部工作总结
2014/11/19 职场文书
2014年销售人员工作总结
2014/11/27 职场文书
幼儿园母亲节活动总结
2015/02/10 职场文书
管理人员岗位职责
2015/02/14 职场文书
建国大业观后感600字
2015/06/01 职场文书
《称赞》教学反思
2016/02/17 职场文书
php字符串倒叙
2021/04/01 PHP
Python函数对象与闭包函数
2022/04/13 Python
Vue router配置与使用分析讲解
2022/12/24 Vue.js