mixin的顺序如何影响派生类? [英] How does the order of mixins affect the derived class?

查看:212
本文介绍了mixin的顺序如何影响派生类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,我有以下混合物通过触摸 dispatch()相互重叠:

Say, I have the following mixins that overlaps with each other by touching dispatch():

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

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

如果我想查看订单,请检查A - >检查B,如果我的代码为 MyView(FooMixin,BarMixin,View) MyView(BarMixin,FooMixin,View)

If I want my view to go through the order, check A -> check B, should my code be MyView(FooMixin, BarMixin, View) or MyView(BarMixin, FooMixin, View)?

为什么我们总是查看或者它们在mixins之后的子类? (我已经注意到这是从阅读django通用视图的源代码,但我不知道背后的理由,如果有的话)

And why do we always put View or its subclasses after mixins? (I have noticed this from reading the source code of the django generic views, but I don't know the rationale behind it, if any)

推荐答案

MRO基本上是深度优先的,从左到右。请参阅新风格的Python类中的方法解析顺序(MRO)更多信息。

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

您可以查看 __ mro __ 属性的类要检查,但 FooMixin 应该首先,如果你想先做检查A。

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()

打印:

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"?

这篇关于mixin的顺序如何影响派生类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆