0

我需要有时显示自定义消息,有时显示应用程序抛出的异常消息。所以,我打算实现类似的东西,但我不知道该怎么做。

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

我想知道是否可以消除重复initstr部分并将它们合并到 A 本身?

4

1 回答 1

0
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
于 2013-08-19T11:45:12.520 回答