如何将“in”关键字扩展到我创建的类?我正在使用 Card 类制作纸牌游戏。还有另一个类是玩家的手。基本上我想看看某张牌是否在手中。一个类比如下:
>>> 5 in range(0, 5)
True
这是我的代码。我有一个 Hand 类,我想看看 Card() 是否在 Hand()
另外,我对这个类的概念很陌生。我才刚刚开始了解这整件事是如何运作的。我是否正确实现了len方法?
class Card:
def __init__(self, suit, rank):
# self.suit > str
# self.rank > str
if (suit in SUITS) and (rank in RANKS):
self.suit = suit
self.rank = rank
else:
self.suit = None
self.rank = None
print "Invalid card:", suit, rank
def __str__(self):
return self.suit + self.rank
def get_suit(self):
return self.suit
def get_rank(self):
return self.rank
# define hand class
class Hand:
# A list of Card objects
# adding cards to the hand should remove cards from the deck.
def __init__(self):
self.hand = []
def __str__(self):
cards = []
for card in self.hand:
cards += [card.get_suit() + card.get_rank()]
return str(cards)
def add_card(self, card):
return self.hand.append(card)
def __len__(self):
counter = 0
for card in self.hand:
counter +=1
return counter
好的,所以我在手类中添加了这段代码:
def __contains__(self, card):
return card in self.hand
但我尝试测试我的代码但它不起作用:
c = Card('H','A')
h = Hand()
h.add_card(Card('S','K'))
h.add_card(Card('D','A'))
h.add_card(Card('H','A'))
print 'hand=', h
print 'c=', c
print 'c in h', c in h
它在终端中显示 False ......为什么?