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处理XML文件的方法
Aug 31 Python
Python深入06——python的内存管理详解
Dec 07 Python
Python实现感知机(PLA)算法
Dec 20 Python
Python实现将数据框数据写入mongodb及mysql数据库的方法
Apr 02 Python
解决Django的request.POST获取不到内容的问题
May 28 Python
Flask Web开发入门之文件上传(八)
Aug 17 Python
python3 property装饰器实现原理与用法示例
May 15 Python
python 实现的发送邮件模板【普通邮件、带附件、带图片邮件】
Jul 06 Python
python类的实例化问题解决
Aug 31 Python
Python tkinter实现图片标注功能(完整代码)
Dec 08 Python
pytorch中 gpu与gpu、gpu与cpu 在load时相互转化操作
May 25 Python
TensorFlow低版本代码自动升级为1.0版本
Feb 20 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
用ODBC的分页显示
2006/10/09 PHP
php SQL防注入代码集合
2008/04/25 PHP
Uchome1.2 1.5 代码学习 common.php
2009/04/24 PHP
PHP session有效期问题
2009/04/26 PHP
PHP 生成的XML以FLASH获取为乱码终极解决
2009/08/07 PHP
apache和php之间协同工作的配置经验分享
2013/04/08 PHP
解析dedeCMS验证码的实现代码
2013/06/07 PHP
解析thinkphp的左右值无限分类
2013/06/20 PHP
php cookie名使用点号(句号)会被转换
2014/10/23 PHP
PHP简单操作MongoDB的方法(安装及增删改查)
2016/05/26 PHP
ThinkPHP 模板引擎使用详解
2017/05/07 PHP
js 图片轮播(5张图片)
2008/12/30 Javascript
js 操作css实现代码
2009/06/11 Javascript
js常用代码段整理
2011/11/30 Javascript
jQuery删除节点的三个方法即remove()detach()和empty()
2013/12/27 Javascript
html文本框提示效果的示例代码
2014/06/28 Javascript
Bootstrap警告(Alerts)的实现方法
2017/03/22 Javascript
JavaScript使用readAsDataURL读取图像文件
2017/05/10 Javascript
Node 升级到最新稳定版的方法分享
2018/05/17 Javascript
vue根据值给予不同class的实例
2018/09/29 Javascript
vue+iview动态渲染表格详解
2019/03/19 Javascript
ES6知识点整理之函数数组参数的默认值及其解构应用示例
2019/04/17 Javascript
Vue的data、computed、watch源码浅谈
2020/04/04 Javascript
利用Vue的v-for和v-bind实现列表颜色切换
2020/07/17 Javascript
Python选择排序、冒泡排序、合并排序代码实例
2015/04/10 Python
解决新django中的path不能使用正则表达式的问题
2018/12/18 Python
pygame实现打字游戏
2021/02/19 Python
python图形开发GUI库pyqt5的详细使用方法及各控件的属性与方法
2020/02/14 Python
Python类绑定方法及非绑定方法实例解析
2020/10/09 Python
python字典与json转换的方法总结
2020/12/28 Python
澳大利亚药房在线:ThePharmacy
2017/10/04 全球购物
领导班子四风表现材料
2014/08/23 职场文书
口才训练演讲稿范文
2014/09/16 职场文书
个人总结与自我评价
2015/02/14 职场文书
小学生学习保证书
2015/02/26 职场文书
macos系统如何实现微信双开? mac登录两个微信以上微信的技巧
2022/07/23 数码科技