2012-06-22 58 views
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) 
下面

是錯誤消息: 回溯(最近通話最後一個): 文件 「C:\ Python27 \ OOP_thecardclass.py」,第29行,在 打印卡1 .cmp(card2) AttributeError:'卡'對象沒有屬性'cmp'蟒蛇 - 類 - AttributeErr - 但方法定義

爲什麼?

+0

'__cmp__'已棄用,請使用各個豐富的比較方法,如果需要,可使用'functools.total_ordering'。另外,不要直接調用它,像往常一樣使用比較運算符。 – agf

回答

2

那一定是__cmp__,不cmp

print card1.__cmp__(card2)