[英]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 2
和Python 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.