'Hand' 对象不支持索引

'Hand' object does not support indexing

我目前正在开发 Blackjack 游戏,按照我目前的结构,我有一个 Hand class,它是 Card 对象的列表,我正在尝试引用特定的纸牌一只手。

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:

的构造函数
class Hand:
    def __init__(self):
        self.hand = []

编辑:我确实在我的主要方法中为每个玩家创建了 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)

您需要像这样定义 dunder 方法 getitem

def __getitem__(self, item):
    return self.hand[item]

否则,当您尝试访问对象的索引时,Python 解释器并不知道您想要做什么。

也定义一个 dunder setitem 也没什么坏处,这样当你尝试这个时:

h = Hand()
h[0] = 1

那么解释器还需要访问 __setitem__ dunder 方法来执行操作。

这些方法已经在内置 list 对象中定义,这就是您可以无缝索引的原因。
您可以尝试从 list class 继承它们。这取决于你,但一个例子会像这样开始:

class Hand(list):
    ...