python相等优先级 [英] python equality precedence
问题描述
class L(object):
def __eq__(self, other):
print 'invoked L.__eq__'
return False
class R(object):
def __eq__(self, other):
print 'invoked R.__eq__'
return False
left = L()
right = R()
使用此代码,左侧获得第一个进行比较,如数据模型中的记录:
With this code, left side gets the first shot at comparison, as documented in the data model:
>>> left == right
invoked L.__eq__
False
但是如果我们使在第6行进行了少许修改(其他所有内容都相同):
But if we make a slight modification on line 6 (everything else the same):
class R(L):
现在,右侧一侧开始比较。
Now the right side gets to have the first shot at comparison.
>>> left == right
invoked R.__eq__
False
为什么?它记录在哪里,什么是设计决定的原因?
Why is that? Where is it documented, and what's the reason for the design decision?
推荐答案
这记录在数字操作,在页面的最下方,并解释了为什么这样做的原因:
This is documented under the numeric operations, further down the page, with an explanation for why it works that way:
注意:如果右操作数的类型是左操作数的子类,并且该子类为操作提供了反映的方法,则此方法将在调用之前左操作数的非反射方法。这种行为允许子类重写其祖先的操作。
Note: If the right operand’s type is a subclass of the left operand’s type and that subclass provides the reflected method for the operation, this method will be called before the left operand’s non-reflected method. This behavior allows subclasses to override their ancestors’ operations.
Python 3文档在您正在查看的部分中还提到了它:
The Python 3 documentation additionally mentions it in the section you were looking at:
如果操作数是不同类型的,并且右操作数的类型是左操作数类型的直接或间接子类,则右操作数的反射方法具有优先级,否则,左操作数的方法具有优先级。不考虑虚拟子类化。
If the operands are of different types, and right operand’s type is a direct or indirect subclass of the left operand’s type, the reflected method of the right operand has priority, otherwise the left operand’s method has priority. Virtual subclassing is not considered.
这篇关于python相等优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!