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

作者:SDFDSJFJ 时间:2022-08-07 15:52:29 

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 &lsquo;int&rsquo;>,很不好看。

为了解决这个问题,可以借助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

来源:https://blog.csdn.net/qq_44980390/article/details/123673310

标签:Python,with,语句,代码,执行,有限次
0
投稿

猜你喜欢

  • SQL Server数据库超级管理员账号防护

    2008-12-22 16:30:00
  • Javascript语法检查插件 jsLint for Vim

    2009-03-11 16:37:00
  • 在Node.js下运用MQTT协议实现即时通讯及离线推送的方法

    2024-05-03 15:54:50
  • Python内置函数dir详解

    2023-05-29 13:38:10
  • JavaScript的目的及历史

    2007-10-17 18:53:00
  • 解决django同步数据库的时候app models表没有成功创建的问题

    2024-01-15 02:04:09
  • Python标准库os常用函数和属性详解

    2022-05-17 21:40:03
  • mysql的group_concat函数使用示例

    2024-01-22 00:10:02
  • python XlsxWriter模块创建aexcel表格的实例讲解

    2023-08-30 02:20:47
  • Python接入MySQL实现增删改查的实战记录

    2023-08-23 04:52:50
  • 教你学会使用Python正则表达式

    2023-01-17 14:08:56
  • Python-apply(lambda x: )的使用及说明

    2022-05-11 04:31:29
  • PHP一文带你搞懂游戏中的抽奖算法

    2024-06-05 09:38:21
  • Python生成数字图片代码分享

    2023-03-02 04:27:18
  • 基于Python实现简单的人脸识别系统

    2021-04-07 17:58:19
  • python 邮件检测工具mmpi的使用

    2022-03-18 04:56:45
  • Mysql 5.6 "隐式转换"导致的索引失效和数据不准确的问题

    2024-01-22 04:07:47
  • Python threading中lock的使用详解

    2023-01-16 08:32:26
  • Python输出带颜色的字符串实例

    2023-08-20 05:28:03
  • python中用Scrapy实现定时爬虫的实例讲解

    2023-07-26 05:47:01
  • asp之家 网络编程 m.aspxhome.com