mixin 的顺序如何影响派生类? [英] How does the order of mixins affect the derived class?
问题描述
比如说,我通过触摸 dispatch()
有以下相互重叠的 mixin:
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,查看)
?
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)
?
为什么我们总是将 View
或其子类放在 mixin 之后?(我通过阅读 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__
属性 要检查的类,但是如果您想先进行检查 A",则应该先FooMixin
.
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
必须放在最后,以便它捕获"任何不在任何 mixin 上的属性查找,而不隐藏这些 mixin 上的任何方法.我不确定我是否理解你问题的那一部分——为什么要添加它"或为什么最后添加"?
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屋!