0
class Card(object):
    suitList = ("Clubs", "Diamonds", "Hearts", "Spades")
    rankList = ("narf", "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King")

    def __init__(self, suit = 0, rank = 2):
        self.suit = suit
        self.rank = rank
    def __str__ (self):
        return "%s of %s" % (self.rankList[self.rank], self.suitList[self.suit])
    # override built-in compare function:
    def __cmp__(self, other):
        # use if instead of if...elif..else
        if self.suit > other.suit: return 1
        if self.suit < other.suit: return -1

        if self.rank == 1 and other.rank != 1: return 1
        if self.rank != 1 and other.rank == 1: return -1
        if self.rank > other.rank: return 1
        if self.rank < otehr.rank: return -1

        return 0

# test code
card1 = Card(0, 12)
card2 = Card(1, 2)
print card1.cmp(card2)

下面是错误消息: Traceback(最近一次调用最后一次):文件“C:\Python27\OOP_thecardclass.py”,第 29 行,打印 card1.cmp(card2) AttributeError: 'Card' object has no attribute 'cmp'

为什么?

4

2 回答 2

2

那一定是__cmp__,不是cmp

print card1.__cmp__(card2)
于 2012-06-22T03:48:46.687 回答
1

__cmp__!= cmp。尝试使用==or!=代替,因为实现的原因__cmp__是针对这些运算符。您不__cmp__直接使用,而是使用它来“重载”运算符。见:http ://en.wikipedia.org/wiki/Ad-hoc_polymorphism

于 2012-06-22T03:49:19.093 回答