Python是==运算符优先级 [英] Python is, == operator precedence
问题描述
在Python3中,
a = b = 3
a is None == b is None
返回False,但是
(a is None) == (b is None)
返回True.因此,我假设仅根据此示例,==优先于 is .
returns True. So I would assume based on this example alone, == has precedence over is.
但是,
a = b = None
a is None == b is None
返回True.还有
(a is None) == (b is None)
返回True.但是
a is (None == b) is None
返回False.在这种情况下,似乎 is 的优先级高于==.
returns False. In this case, it would seem as if is has precedence over ==.
再举一个例子,这个表达式并不意味着要做什么,但是请忍受.如果我说
To give another example, and this expression isn't meant to do anything, but bear with me please. If I say
None is None == None
它返回True.但是以下两个都返回False.
it returns True. But both of the following return False.
None is (None == None)
(None is None) == None
很明显,Python并没有以严格的优先级来评估它们,但是我对正在发生的事情感到困惑.如何使用2个不同的运算符来评估此表达式,但与任一顺序都不相同?
So clearly, Python isn't evaluating these with some strict precedence, but I'm confused what is going on. How is it evaluating this expression with 2 different operators, but differently from either order?
推荐答案
您在这里看到的是操作员链接,根本没有优先级!
What you see here is operator chaining and there is no precedence involved at all!
Python支持类似的表达式
Python supports expressions like
1 < a < 3
测试数字是否在1到3之间;它等于(1 < a) and (a < 3)
,除了a
仅被评估一次.
To test that a number is in between 1 and 3; it's equal to (1 < a) and (a < 3)
except that a
is only evaluated once.
不幸的是,这也意味着例如
Unfortunately that also means that e.g.
None is None == None
实际上是指
(None is None) and (None == None)
这当然是对的,而您开始时使用的更长的示例
which is of course True, and the longer example you started with
a = b = 3
a is None == b is None
表示
(a is None) and (None == b) and (b is None)
,如果a
和b
均为None
,则只能为True
.
which can only be True
if both a
and b
are None
.
文档此处,请参见有关链接的内容.
Documentation here, see the bit about chaining.
有时非常有用,但在您最不期望的时候也会弹出!
Very useful sometimes but it also pops up when you least expect it!
这篇关于Python是==运算符优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!