Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

like image 976
Jonathan Avatar asked Apr 23 '26 14:04

Jonathan


1 Answers

__cmp__ (Python 2.x only) should return negative for self < other, zero for self == other and positive for self > other.

The others ("rich comparison methods", 2.x and 3.x) should return appropriate booleans, e.g. __lt__(self, other) should return True when self < other, False otherwise.

like image 159
jonrsharpe Avatar answered Apr 25 '26 04:04

jonrsharpe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!