Comparisons
There are eight comparison operations in Python. They all have the same priority (which is higher than that of the Boolean operations). Comparisons can be chained arbitrarily; for example, x < y <= z
is equivalent to x < y andy <= 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).
翻译:比较运算符
Python中有八种比较运算符。它们拥有相同的优先级(它们比bool关系运算符的优先级要高)。比较运算符可以连续的如
链式的进行比较;比如 x<y<=z 等价于 x<y and y <= z,但是y表达式只会进行一次计算(但是,如果x<y的表达式为false
,那么两者都不会计算z的表达式)
下面的表格简单是描述了运算符。
前面省略
is 是否是同一个对象
is not 是否为不同的对象
This table summarizes the comparison operations:
Operation | Meaning |
---|---|
< |
strictly less than |
<= |
less than or equal |
> |
strictly greater than |
>= |
greater than or equal |
== |
equal |
!= |
not equal |
is |
object identity |
is not |
negated object identity |
Objects of different types, except different numeric types, never compare equal. Furthermore, some types (for example, function objects) support only a degenerate notion of comparison where any two objects of that type are unequal. The <
, <=
, >
and >=
operators will raise a TypeError
exception when comparing a complex number with another built-in numeric type, when the objects are of different types that cannot be compared, or in other cases where there is no defined ordering.
Non-identical instances of a class normally compare as non-equal unless the class defines the __eq__()
method.
Instances of a class cannot be ordered with respect to other instances of the same class, or other types of object, unless the class defines enough of the methods __lt__()
, __le__()
, __gt__()
, and __ge__()
(in general, __lt__()
and __eq__()
are sufficient, if you want the conventional meanings of the comparison operators).
The behavior of the is
and is not
operators cannot be customized; also they can be applied to any two objects and never raise an exception.
Two more operations with the same syntactic priority, in
and not in
, are supported only by sequence types (below).
a=1
b=2
c=1
print(a is b,a is not b,a is c ,a is not c)
输出
False True True False
除了数字以外的其他对象不会进行比较。除此之外,有些类型(比如:方法对象)只支持一部分的比较,对于比较两个不同类型的对象. 当使用复数与其他数字类型,或当两个不同的类型进行比较,或者没有定义比较规则的时候
在进行> >= < <=比较时会抛出类型异常TypeError。
不同数据类型之间一般不进行比较除非定了__eq__方法。
即使是相同类型的对象,如果没有定义重载对应的方法也不能进行比较。如果想要方便比较的话可以自行定义。
is 和 is not不支持自定义比较,它们支持所有的不同的规则,并且不会抛出异常。
多个操作之间没有优先级的差异。关键字 in 和 not in只适用于序列。