Comparing cards

For built-in types, there are conditional operators (<, >, ==, etc.) that compare values and determine when one is greater than, less than, or equal to another. For user-defined types, we can override the behavior of the built-in operators by providing a method named __cmp__. But in Python 3+, the cmp() function should be treated as gone, and the __cmp__() special method is no longer supported. Use __lt__() for sorting, __eq__() with __hash__(), and other rich comparisons as needed. (If you really need the cmp() functionality, you could use the expression (a > b) - (a < b) as the equivalent for cmp(a, b).)

The cmp method takes two parameters, self and other, and returns a positive number if the first object is greater, a negative number is the second object is greater, and 0 if they are equal to each other. The correct ordering for cards is not obvious. For example, which is better, the 3 of Clubs or the 2 of Diamonds? One has a higher rank, but the other has a higher suit. In order to compare cards, you have to decide whether rank or suit is more important.

The answer might depend on what game you are playing, but to keep things simple, we’ll make the arbitrary choice that suit is more important, so all of the Spades outrank all of the Diamonds, and so on.

def cmp(self,other):
t1 = (self.suit,self.rank)
t2 = (other.suit,other.rank)
return (t1 > t2) - (t1 < t2)

Comparing cards

from Thinking in Python

上一篇:【Android】Android实现截取当前屏幕图片并保存至SDCard


下一篇:C语言的文件读写操作函数小结