在mixin中访问基类super

2024-10-02 06:29:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我的类结构如下所示:

class Question(object):
    def answer(self):
        return "Base Answer"

class ExclaimMixin(object):
    def answer(self):
        return "{}!".format(super(ExclaimMixin, self).answer())

class ExpressiveQuestion(Question, ExclaimMixin)
    pass

我希望ExclaimMixin中的answer方法在ExpressiveQuestion中被调用时能够访问Question中的{},这样它将返回"Base Answer!"。在

显然,在这种情况下,可以通过将ExclaimMixin中的answer方法改为ExpressiveQuestion来解决这个问题,但在某些情况下这是不可能的(例如,在类结构中有更多的深度和分支)。在

使用mixin可以实现这个结果吗,还是只能通过破坏基类树来实现?在


Tags: 方法answerselfformatbasereturnobjectdef
2条回答

这种方法难道不更清楚吗?你定义了问题的内容,然后在惊叹号mixin中定义了一个你想要应用mixin的问题内容(一些有意义的东西),然后在ExpresiveQuestion中混合它们。在

class Question(object):
    def answer(self):
        return "Base Answer"

class ExclaimMixin(object):
    def exclaim(self, answer):
        return "{}!".format(answer)

class ExpressiveQuestion(Question, ExclaimMixin):
    def expresive_question(self):
        return self.exclaim(self.answer())

在[1]:来自应答导入*

在[2]中:eq=ExpressiveQuestion()

在[3]:情商表达问题() 出局[3]:“基本回答!”在

使用mixin时,您需要记住基类顺序的简单规则-“从右到左”。这意味着,所有mixin都应该在实际基类之前。在

class Question(object):
    def answer(self):
        return "Base Answer"

class ExclaimMixin(object):
    def answer(self):
        return "{}!".format(super(ExclaimMixin, self).answer())

class ExpressiveQuestion(ExclaimMixin, Question)
    pass

>>> q = ExpressiveQuestion()
>>> q.answer()
'Base Answer!'

相关问题 更多 >

    热门问题