自定义Python异常:名称不同但任务相同
我要求有时显示自定义消息,有时显示应用程序抛出的异常消息。所以,我计划实现类似的东西,但我不知道如何做到这一点自定义Python异常:名称不同但任务相同,python,exception-handling,Python,Exception Handling,我要求有时显示自定义消息,有时显示应用程序抛出的异常消息。所以,我计划实现类似的东西,但我不知道如何做到这一点 class A(Exception): """Base class for exceptions in this module.""" pass class B(A): """Expect a custom message here.""" def __init__(self, err_msg): super(B, self).__i
class A(Exception):
"""Base class for exceptions in this module."""
pass
class B(A):
"""Expect a custom message here."""
def __init__(self, err_msg):
super(B, self).__init__(err_msg)
self.err_msg = err_msg
def __str__(self):
return self.err_msg
class C(A):
"""Expect a custom message here."""
def __init__(self, err_msg):
super(C, self).__init__(err_msg)
self.err_msg = err_msg
def __str__(self):
return self.err_msg
class D(A):
"""Expect the default behavior here."""
pass
我想知道的是,我是否可以消除重复的init和str部分,并将它们合并到一个自身中?完全没有必要实现
\uu str
<代码>异常已经提供了一种传递自定义消息的方法:>>引发异常(“自定义消息”)回溯(最后一次调用):文件“”,第1行,在异常中:自定义消息
我希望您不是为了提供自定义消息而对进行子类化的,在这种情况下,我只需删除子类并直接使用A
。
class MyException(Exception):
"""Expect a custom message here."""
def __init__(self, err_msg):
super(MyException, self).__init__(err_msg)
self.err_msg = err_msg
def __str__(self):
return self.err_msg
def CustomExceptionA(MyException):
pass
def CustomExceptionB(MyException):
pass