我是编程初学者,由于我现在正在做练习,所以在异常的基础知识方面遇到了一些麻烦。
练习分为两个部分:
A部分:
我需要创建一个名为 ExceptionCounter 的类,其中包含一个实例变量 num_exceptions,它从 0 开始。ExceptionCounter 还有一种方法,它采用一个参数,即一个函数(除了通常的 self 之外)。check_for_exception 调用该函数(不带参数),并在引发任何异常时递增 num_exceptions。
除了“如果引发任何异常”部分之外,我已经掌握了代码的基本内容。我正在传递一个函数,其中函数体是一个对象,对吗?因此,如果我传递的函数有错误,我该如何处理该错误以触发增量?
到目前为止,这是我的代码:
class ExceptionCounter(Exception):
def __init__(self):
self.num_exceptions = 0
def check_for_exceptions(self, func):
try:
self.func()
except Exception:
self.num_exceptions += 1
Run Code Online (Sandbox Code Playgroud)
但我收到“ExceptionCounter”对象没有属性“check_for_exception”错误。有想法该怎么解决这个吗?
python ×1