我有课

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时遇到很多麻烦。

最佳答案

被这种类型覆盖的方法怎么样:

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时,它“起作用”

09-06 13:18