奇数运算符 precedence/associativity 行为

Odd operator precedence/associativity behaviour

为什么在Python2.7中,下面

True == 'w' in 'what!?'

行为不同于两者

(True == 'w') in 'what!?'

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

在Python中比较可以是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).

所以你的代码实际上等同于

>>> (True == 'w') and ('w' in 'what!?')
False

一起来看看:

>>> 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!?')]))"

这是一个chained comparison:

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 [...]