问题
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
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?
回答1:
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.
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.
来源:https://stackoverflow.com/questions/34543909/python-equality-precedence