问题
How is it that, in Python 2.7, the following
True == 'w' in 'what!?'
behaves differently than both
(True == 'w') in 'what!?'
and
True == ('w' in 'what!?')
?
>>> True == 'w' in 'what!?'
False
>>> (True == 'w') in 'what!?'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not bool
>>> True == ('w' in 'what!?')
True
回答1:
In Python, comparisons can be chained together:
Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).
So your code is actually equivalent to
>>> (True == 'w') and ('w' in 'what!?')
False
回答2:
Let's take a look:
>>> import ast
>>> ast.dump(ast.parse("""True == 'w' in 'what!?'""", mode='eval'))
"Expression(body=Compare(left=Name(id='True', ctx=Load()), ops=[Eq(), In()],
comparators=[Str(s='w'), Str(s='what!?')]))"
This is a chained comparison:
Comparisons can be chained arbitrarily, e.g.,
x < y <= z
is equivalent tox < y and y <= z
, except thaty
is evaluated only once [...]
来源:https://stackoverflow.com/questions/28071165/odd-operator-precedence-associativity-behaviour