Skip to main content
 首页 » 编程设计

python之大于/小于 Python 中的比较

2025年05月04日9langtianya

在一个类中实现丰富的比较方法时,比较两个不同的类类型应该返回什么?从文档中说

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 either enough of the rich comparison methods (__lt__(), __le__(), __gt__(), and __ge__()) or the __cmp__() method.

但是,我在文档中找不到任何地方提到用于比较两个不同类的标准返回类型。我想知道 Python 2 和 Python 3 的标准。

请您参考如下方法:

__cmp__ ( Python 2.x only ) 应该为 self < other 返回负值, self == other 为零对 self > other 呈阳性.

The others (“丰富的比较方法”,2.x 和 3.x)应该返回适​​当的 bool 值,例如__lt__(self, other)应该返回 True什么时候self < other , False否则。