[Tutor] The Card Game

Steven D'Aprano steve at pearwood.info
Fri Jul 1 04:15:45 CEST 2011


Christopher King wrote:
> I would go with __cmp__ which covers them all. 1 for greater, 0 for equal,
> -1 for less than.


So-called "rich comparisons" using __lt__, __gt__, etc. have been 
preferred since Python 2.1. The major advantage of them is that they can 
be used for more complicated data types, e.g. with sets where > means 
superset and < means subset:


 >>> a = set([1, 2, 3, 4])
 >>> b = set([2, 3, 4, 5])
 >>>
 >>> a < b  # a is not a subset of b
False
 >>> a > b  # neither is it a superset
False
 >>> a == b  # and they're not equal either
False
 >>> a & b  # but they do overlap:
set([2, 3, 4])



In Python 2.x, __cmp__ is only used as a fall-back if the rich 
comparisons aren't defined. In Python 3.x, __cmp__ is gone: even if you 
define it, it won't be used.





More information about the Tutor mailing list