[英]python - class - AttributeErr - but method defined
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)
below is the err msg: Traceback (most recent call last): File "C:\\Python27\\OOP_thecardclass.py", line 29, in print card1.cmp(card2) AttributeError: 'Card' object has no attribute 'cmp' 下面是err消息:追溯(最近一次调用是最近的):文件“ C:\\ Python27 \\ OOP_thecardclass.py”,第29行,在打印card1.cmp(card2)中AttributeError:'Card'对象没有属性'cmp'
Why? 为什么?
那必须是__cmp__
,而不是cmp
:
print card1.__cmp__(card2)
__cmp__
!= cmp
. __cmp__
!= cmp
。 Try using ==
or !=
instead, as the reason for implementing __cmp__
is for these operators. 尝试改用
==
或!=
,因为实现__cmp__
的原因是针对这些运算符。 You don't use __cmp__
directly, you use it to "overload" operators. 您不直接使用
__cmp__
,而是使用它来“重载”运算符。 See: http://en.wikipedia.org/wiki/Ad-hoc_polymorphism 请参阅: http : //en.wikipedia.org/wiki/Ad-hoc_polymorphism
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.