Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
自定义Python异常:名称不同但任务相同_Python_Exception Handling - Fatal编程技术网

自定义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

我想知道的是,我是否可以消除重复的initstr部分,并将它们合并到一个自身中?

完全没有必要实现
\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