我的类结构如下所示:
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可以实现这个结果吗,还是只能通过破坏基类树来实现?在
这种方法难道不更清楚吗?你定义了问题的内容,然后在惊叹号mixin中定义了一个你想要应用mixin的问题内容(一些有意义的东西),然后在ExpresiveQuestion中混合它们。在
在[1]:来自应答导入*
在[2]中:eq=ExpressiveQuestion()
在[3]:情商表达问题() 出局[3]:“基本回答!”在
使用mixin时,您需要记住基类顺序的简单规则-“从右到左”。这意味着,所有mixin都应该在实际基类之前。在
相关问题 更多 >
编程相关推荐