How does the order of mixins affect the derived class?

隐身守侯 提交于 2019-11-27 07:04:21
agf

The MRO is basically depth-first, left-to-right. See Method Resolution Order (MRO) in new style Python classes for some more info.

You can look at the __mro__ attribute of the class to check, but FooMixin should be first if you want to do "check A" first.

class UltimateBase(object):
    def dispatch(self, *args, **kwargs):
        print 'base dispatch'

class FooMixin(object):
    def dispatch(self, *args, **kwargs):
        print 'perform check A'
        return super(FooMixin, self).dispatch(*args, **kwargs)

class BarMixin(object):
    def dispatch(self, *args, **kwargs):
        print 'perform check B'
        return super(BarMixin, self).dispatch(*args, **kwargs)

class FooBar(FooMixin, BarMixin, UltimateBase):
    pass

FooBar().dispatch()

Prints:

perform check A
perform check B
base dispatch

View has to be last so that it "catches" any attribute lookups that weren't on any mixins, without hiding any methods on those mixins. I'm not sure I understand that part of your question -- what it "why is it added at all" or "why is it added last"?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!