Odd operator precedence/associativity behaviour [duplicate]

只愿长相守 提交于 2019-12-11 01:45:19

问题


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 to x < y and y <= z, except that y is evaluated only once [...]



来源:https://stackoverflow.com/questions/28071165/odd-operator-precedence-associativity-behaviour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!