简体   繁体   English

Python 中的大于/小于比较

[英]Greater/Less Than Comparison in Python

When implementing the rich comparison methods in a class, what should be returned when comparing two different class types?在一个类中实现丰富的比较方法时,比较两个不同的类类型时应该返回什么? From the documentation it says从它说的文档

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.类的实例不能相对于同一类的其他实例或其他类型的对象进行排序,除非该类定义了足够丰富的比较方法( __lt__()__le__()__gt__()__ge__() ) 或__cmp__()方法。

However, I can't find anywhere in the documentation where it mentions the standard return type for comparison between two different classes.但是,我在文档中找不到任何提到用于比较两个不同类的标准返回类型的地方。 I'd like to know the standard for both Python 2 and Python 3 .我想知道Python 2Python 3的标准。

__cmp__ ( Python 2.x only ) should return negative for self < other , zero for self == other and positive for self > other . __cmp__仅限 Python 2.x )应为self < other返回负数,为self == other返回零,为self > other正数。

The others ("rich comparison methods", 2.x and 3.x) should return appropriate booleans, eg __lt__(self, other) should return True when self < other , False otherwise. 其他(“丰富的比较方法”,2.x 和 3.x)应该返回适​​当的布尔值,例如__lt__(self, other)应该在self < other时返回True ,否则返回False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM