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?
Answer: The correct order of precedence is given by PEMDAS which means Parenthesis (), Exponential **, Multiplication *, Division /, Addition +, Subtraction -.
Python follows the same precedence rules for its mathematical operators that mathematics does. Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first, 2 * (3-1) is 4, and (1+1)**(5-2) is 8.
All comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With