Python3 比较运算符

Python3 comparison operators

Python3 不支持不同数据类型之间的比较
1 < '1' 将执行:

`TypeError: '<' not supported between instances of 'float' and 'str'`

但为什么 1 == '1'(或类似 156 == ['foo'])returns False

因为检查某些东西是否等于其他东西(或者是其他东西)是有意义的,即使它们不是同一类型。但是,如果它们不是同一类型,检查哪个“数量”更大没有多大意义,因为“数量”可能以不同的方式为每种类型定义(换句话说,“数量”可能测量物体的不同质量)。

一个non-code例子:一个苹果显然不能==一个橙子。但是,如果我们将苹果的“量”定义为它的“红度”,将橙子的“量”定义为它的“味”,我们就无法检查苹果是否比橙子> . > 将尝试比较这些对象的不同品质。

回到代码: 很明显 4 不是(或不等于)列表 [4]。但是像 4 > [4] 这样的支票有什么意义呢?列表中的整数“更小”或“更大”是什么意思?

来自文档:

The default behavior for equality comparison (== and !=) is based on the identity of the objects. Hence, equality comparison of instances with the same identity results in equality, and equality comparison of instances with different identities results in inequality. A motivation for this default behavior is the desire that all objects should be reflexive (i.e. x is y implies x == y).

有时我们想知道两个变量是否相同,这意味着它们指的是同一个对象,例如True is True 会 return True,但另一方面 "True" is True return 会 False,因此 "True" == True returns False(我没有提供使用 is 运算符的最佳用例,此示例将在 Python3.8+ 中引发 SyntaxWarning,但这是主要思想)