我目前正在制作一个二十一点游戏,而且由于我目前已经有了它的结构,我有一个Hand类,它是一个Card对象列表,我试图在手中引用一张特定的卡片。 / p>
def get_move(self):
if self.balance > self.bet and not self.isSplit:
if self.hand[0].point == self.hand[1].point:
问题出现在第三行。我收到以下错误:
Traceback (most recent call last):
File "driver.py", line 126, in <module>
player.get_move()
File "/home/ubuntu/workspace/finalproject/human_player.py", line 29, in get_move
if self.hand[0].point == self.hand[1].point:
TypeError: 'Hand' object does not support indexing
为什么不让我的索引通过Hand?这是我的Hand类的构造函数:
class Hand:
def __init__(self):
self.hand = []
编辑:我在主方法中为每个玩家创建了手形对象:
# creating the dealer for the game
dealer_hand = hand.Hand()
dan_the_dealer = dealer.Dealer(dealer_hand)
# for however many players you start with, add each new player to an array of players
for i in range(num_players):
player_name = input("\nWhat is Player %i's name?\n" % (i+1))
new_hand = hand.Hand()
new_player = human_player.HumanPlayer(player_name, starting_balance, 0, new_hand)
players.append(new_player)
答案 0 :(得分:1)
你需要像这样定义dunder方法getitem
def __getitem__(self, item):
return self.hand[item]
否则,当您尝试访问对象的索引时,Python解释器并不真正知道您想要做什么。
也不会定义一个dunder setitem,所以当你尝试这个时:
h = Hand()
h[0] = 1
然后解释器还需要访问__setitem__
dunder方法来执行操作。
这些方法已在内置list
对象中定义,这就是您可以无缝索引的原因。
您可以尝试从list
类继承它们。这取决于你,但是一个例子就像:
class Hand(list):
...