Python 是,== 运算符优先级

Python is, == operator precedence

在Python3,

a = b = 3
a is None == b is None

returns 错误,但是

(a is None) == (b is None)

returns 正确。所以我假设仅基于这个例子,== 优先于 is.

然而,

a = b = None
a is None == b is None

returns 正确。并且

(a is None) == (b is None)

returns 正确。但是

a is (None == b) is None

returns 错误。在这种情况下,似乎 is 优先于 ==.

再举个例子,这个表达式没有任何意义,但请多多包涵。如果我说

None is None == None

它return是真的。但是下面两个return都错了。

None is (None == None)
(None is None) == None

很明显,Python 并没有按照严格的优先顺序评估这些,但我对发生的事情感到困惑。如何使用 2 个不同的运算符评估此表达式,但顺序不同?

您在这里看到的是运算符链接,根本不涉及优先级!

Python 支持

这样的表达式
1 < a < 3

测试一个数字是否在1到3之间;它等于 (1 < a) and (a < 3) 除了 a 只计算一次。

不幸的是,这也意味着例如

None is None == None

其实就是

(None is None) and (None == None)

这当然是正确的,而且你开始的例子更长

a = b = 3
a is None == b is None

表示

(a is None) and (None == b) and (b is None)

如果ab都是None.

,则只能是True

文档 here,请参阅有关链接的内容。

有时非常有用,但它也会在您最意想不到的时候弹出!

根据文档,所有 python comparisons operators 具有相同的优先级:

There are eight comparison operations in Python. They all have the same priority (which is higher than that of the Boolean operations).

然而,通过用括号包裹比较,它们开始成为 atoms expressions,所以括号内的语句在外面的语句之前评估,这会影响评估的顺序,我将分解第一个 "contradictional" case,其他类似:

a = b = 3
a is None == b is None

根据文档,优先级相同,因此下一步是评估:

1. a is None ? -> False # Because a == 3
2. False == b -> False # Because b == 3
3. False is None

请看下面第二种情况的顺序:

(a is None) == (b is None)

1. a is None ? -> False # Because a == 3
2. b is None -> False # Because b == 3
3. False is False -> True