关于python:python – 类 – AttributeErr – 但是定义了方法

python - class - AttributeErr - but method defined

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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)

下面是错误信息:(最近的电话追踪:last)文件的"C: python27 OOP _线29,在thecardclass.py"打印card1.cmp(card2)attributeerror卡的蛛网膜下腔出血(SAH):"对象属性"(CMP)

为什么?


必须是__cmp__,而不是cmp

1
print card1.__cmp__(card2)

EDOCX1,0!=cmp。尝试使用==!=,因为实施__cmp__的原因是为了这些操作员。您不直接使用__cmp__,而是使用它来"重载"运算符。参见:http://en.wikipedia.org/wiki/ad-hoc_多态性