Python 如何提供在类的错误处理方法中发生错误的反馈?
我正在使用python中的一个类,它是一个更大程序的一部分。该类正在调用不同的方法 如果在我希望代码继续运行的某个方法中存在错误,但在程序完成后,我希望能够看到哪些方法中存在潜在错误 下面是我目前构造它的大致方式,这个解决方案不能很好地与更多方法进行扩展。是否有更好的方法(在代码完全运行后)提供反馈,以确定哪种方法存在潜在错误Python 如何提供在类的错误处理方法中发生错误的反馈?,python,Python,我正在使用python中的一个类,它是一个更大程序的一部分。该类正在调用不同的方法 如果在我希望代码继续运行的某个方法中存在错误,但在程序完成后,我希望能够看到哪些方法中存在潜在错误 下面是我目前构造它的大致方式,这个解决方案不能很好地与更多方法进行扩展。是否有更好的方法(在代码完全运行后)提供反馈,以确定哪种方法存在潜在错误 class Class(): def __init__(self): try: self.method_1()
class Class():
def __init__(self):
try:
self.method_1()
except:
self.error_method1 = "Yes"
break
try:
self.method_2()
except:
self.error_method2 = "Yes"
break
try:
self.method_3()
except:
self.error_method3 = "Yes"
break
尽管如我在评论中提到的,当出现异常时,您可以使用来检索有关异常的信息,但可能不需要这样做,因为Python的标准try
/expect
机制似乎已经足够了
下面是一个可运行的示例,展示了如何这样做,以便在以后提供有关类的几个方法的执行的“反馈”。这种方法使用一个decorator函数,因此应该可以很好地扩展,因为同一个decorator可以根据需要应用于任意多个类的方法
from contextlib import contextmanager
from functools import wraps
import sys
from textwrap import indent
def provide_feedback(method):
""" Decorator to trap exceptions and add messages to feedback. """
@wraps(method)
def wrapped_method(self, *args, **kwargs):
try:
return method(self, *args, **kwargs)
except Exception as exc:
self._feedback.append(
'{!r} exception occurred in {}()'.format(exc, method.__qualname__))
return wrapped_method
class Class():
def __init__(self):
with self.feedback():
self.method_1()
self.method_2()
self.method_3()
@contextmanager
def feedback(self):
self._feedback = []
try:
yield
finally:
# Example of what could be done with any exception messages.
# They could instead be appended to some higher-level container.
if self._feedback:
print('Feedback:')
print(indent('\n'.join(self._feedback), ' '))
@provide_feedback
def method_1(self):
raise RuntimeError('bogus')
@provide_feedback
def method_2(self):
pass
@provide_feedback
def method_3(self):
raise StopIteration('Not enough foobar to go around')
inst = Class()
输出:
反馈:
类中发生RuntimeError('bogus')异常。方法_1()
类中发生StopIteration(“没有足够的foobar来遍历”)异常。方法_3()
您不需要手动执行此操作,异常中的堆栈跟踪会告诉您让我澄清一下。这一类是更大代码的一部分。如果其中一个方法中存在错误,代码将继续工作。它应该只提供直接反馈,以便我以后可以修复它。当出现异常时,您可以调用except:
子句以获取有关发生情况的信息。在这一点上,你可以用它做任何你想做的事。我不认为这是他的问题。他想对他的类的所有方法调用使用相同的消息?所以你想发明你自己的应用程序错误记录器?MathiasRa:这符合你的要求吗?