与异常

时间:2018-03-22 04:31:33

标签: python inheritance exception

我上课了。

class IncorrectOfferDetailsOfferException(Exception):
    def __init__(self, offer):
        self.offerName = offer[0]
        self.offerType = offer[1]
        self.message = "Offer \"" + self.offerName + "\" could not be completed. It appears to be of type \"" + self.offerType + "\", but this may be what is wrong and causing the exception."
        super(IncorrectOfferDetailsOfferException, self).__init__(self.message)

我想写一个更通用的类来扩展它。

class BadOfferException(Exception):
    def __init__(self, offer):
        self.offerName = offer[0]
        self.offerType = offer[1]
        self.message = "Offer \"" + self.offerName + "\" caused a problem."

如何将这两者联系起来以删除冗余代码并使用更具体的代码覆盖更一般的消息文本?你知道,类继承。我很难理解如何以正确的方式使用super

2 个答案:

答案 0 :(得分:1)

子类型覆盖的方法怎么样:

class BadOfferException(Exception):
    def __init__(self, offer):
        self.offerName = offer[0]
        self.offerType = offer[1]
        self.message = self._construct_message()
        super(BadOfferException, self).__init__(self.message)

    def _construct_message(self):
        return 'Offer "{}" caused a problem'.format(self.offerName)


class IncorrectOfferDetailsOfferException(BadOfferException):
    def _construct_message(self):
        return 'Offer "{}" could not be completed. It appears to be of type "{}", but this may be what is wrong and causing the exception.'.format(self.offerName, self.offerType)

然后当你举起IncorrectOfferDetailsOfferException时,它只是“有效”

答案 1 :(得分:1)

首先,您创建子类的方式是通过顶部的基类列表:

class BadOfferException(Exception):
    # etc.

class IncorrectOfferDetailsOfferException(BadOfferException):
    # etc.

我刚刚用Exception替换了BadOfferException。 (我们不需要两者,因为BadOfferException已经是Exception的子类了。你必须先声明超类,然后再声明子类,所以我切换了顺序。

现在,您将要使超类的实现更加通用,因此子类只能覆盖它关心的部分。唯一不同的是消息,对吗?所以允许传入:

class BadOfferException(Exception):
    def __init__(self, offer, message=None):
        self.offerName = offer[0]
        self.offerType = offer[1]
        if message is None:
            message = "Offer \"" + self.offerName + "\" caused a problem."
        self.message = message

现在,你需要通过super传递所有内容。这意味着我们无法使用offerNameofferType,因为它们尚未定义,但这不是问题:

class IncorrectOfferDetailsOfferException(BadOfferException):
    def __init__(self, offer):
        message = "Offer \"" + offer[0] + "\" could not be completed. It appears to be of type \"" + offer[1] + "\", but this may be what is wrong and causing the exception."
        super(IncorrectOfferDetailsOfferException, self).__init__(offer, message)

这就是你需要做的一切。

但是,当我们参与其中时,您可能希望将BadOfferException变为Exception的更好的子类。人们希望能够在args实例上看到Exception - 这不是强制性的;你可以把它关掉,它只是一个空元组,但它很好。您可以致电super(BadOfferException, self).__init__(offer)