Skip to main content
 首页 » 编程设计

python之错误的子类,计算它被引发的次数

2024年09月07日8webabcd

脚本中的某个错误消息当前正被 try except block 捕获。对于预期用途,这将使错误发生得太频繁,我想知道是否有一种简洁的方法可以从错误中创建一个子类,该子类计算在触发之前发生了多少次。

以下说明了所需的行为。没有任何处理:

from random import randint 
for i in range(100): 
    print(1 / randint(0, 10)) 

输出:

0.1111111111111111 
0.1 
0.25 
0.3333333333333333 
0.1 
0.2 
0.16666666666666666 
1.0 
0.1 
0.5 
1.0 
 
--------------------------------------------------------------------------- 
ZeroDivisionError                         Traceback (most recent call last) 
<ipython-input-11-bfba3ff98af3> in <module>() 
      1 from random import randint 
      2 for i in range(100): 
----> 3     print(1 / randint(0, 10)) 
 
ZeroDivisionError: division by zero 

你能以某种方式做到这一点吗:

class MoreThanFiveZeroDiv(ZeroDivisionError): 
    pass 

当你运行这个时:

from random import randint 
for i in range(100): 
    try: 
         print(1 / randint(0, 10)) 
    except MoreThanFiveZeroDiv 

它只在发生第五次时触发?

请您参考如下方法:

对于此任务,您基本上不需要自定义异常类。相反,您可以使用计数器变量并增加它直到它满足您的预期约束:

In [41]: counter = 0 
 
In [42]: from random import randint 
    ...: for i in range(100): 
    ...:     try: 
    ...:         print(1 / randint(0, 10)) 
    ...:     except ZeroDivisionError as exc: 
    ...:         if counter > 5: 
    ...:             raise Exception("More thatn 5 times ZeroDivisionError!") 
    ...:         counter += 1 

如果您正在寻找更简洁的方法,您可以使用自定义类在其中存储计数器并在其内部处理条件检查:

In [57]: class MoreThanFiveZeroDiv:   
    ...:     def __init__(self): 
    ...:         self.counter = 0 
    ...:                              
    ...:     def __call__(self, exc): 
    ...:         if type(exc) is ZeroDivisionError: 
    ...:             if self.counter > 5: 
    ...:                 raise exc 
    ...:             self.counter += 1 
    ...:         else: 
    ...:             raise exc 

然后你可以像下面这样使用它:

 mtfz = MoreThanFiveZeroDiv() 
 
for i in range(100): 
    try: 
        print(1 / randint(0, 10)) 
    except Exception as exc: 
        mtfz(exc)