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

使用此代码,左侧首先进行比较,如数据模型中的 documented

>>> left == right
invoked L.__eq__
False

但是如果我们在第 6 行稍微修改一下(其他都一样):

class R(L):

现在 一方在比较时获得第一枪。

>>> left == right
invoked R.__eq__
False

这是为什么?它在哪里记录,设计决定的原因是什么?

这在 numeric operations 下有记录,在页面的下方,解释了为什么这样工作:

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 documentation 在您查看的部分中另外提到了它:

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.