'Hand' object does not support indexing

1.9k views Asked by At

I'm currently working on a Blackjack game, and as I currently have it structured, I have a Hand class that is a list of Card objects, and I am trying to reference a specific card in a hand.

def get_move(self):
    if self.balance > self.bet and not self.isSplit:
        if self.hand[0].point == self.hand[1].point:

The problem arises on that third line. I'm getting the following error:

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

Why isn't it letting my index through the Hand? Here is the constructor to my Hand class:

class Hand:
    def __init__(self):
        self.hand = []

EDIT: I do create Hand objects for each of the players in my main method:

# 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)
1

There are 1 answers

1
Vasili Syrakis On BEST ANSWER

You need to define the dunder method getitem like so

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

Otherwise, when you try to access the index of the object, the Python interpreter doesn't really know what you want to do.

Wouldn't hurt to also define a dunder setitem too so that when you try this:

h = Hand()
h[0] = 1

then the interpreter will also need to access the __setitem__ dunder method to perform the operation.

These methods are already defined in the builtin list object and that's why you can index seamlessly.
You could try to inherit them from the list class. That's up to you, but an example would begin like:

class Hand(list):
    ...