2016-12-11 1 views
0

현재 블랙 잭 게임을하고 있으며 현재 구조화되어 있으므로 Card 객체 목록 인 Hand 클래스가 있으며 특정 클래스를 참조하려고합니다. 손에 카드.'Hand'객체가 인덱싱을 지원하지 않습니다.

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 

왜 손을 통해 내 색인을 보내지 않습니까? 여기 내 손 클래스에 생성자는 다음과 같습니다

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

어디에서나'Hand' 객체에 대해'hand'를 재정의하지 않습니까? – Iluvatar

+0

그 에러 메시지는'self.hand'가리스트가 아니라'Hand' 객체라는 것을 나타냅니다. 당신이 보여준 코드에서 그 일이 일어나지는 않을 것입니다. 따라서 문제는 보여주지 않는 코드에 있습니다. 버그가 포함 된 코드가 표시되지 않으므로 아무도 도움을 줄 수 없습니다. –

+0

나는 그렇게 믿지 않는다. 내가 그 표식을 찾는다면 그 표정은 어떻게 될 것입니까? – macschmidt33

답변

1

당신은 그래서 같은 던더 방법의 getItem를 정의 할 필요가 : 내 주요 방법으로 선수 각각에 대해 손 객체를 생성 할

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

그렇지 않으면 개체의 인덱스에 액세스하려고 할 때 파이썬 인터프리터는 사용자가 원하는 것을 실제로 알지 못합니다. 당신이 때 있도록

도 너무 던더의 setitem을 정의 할 다치게하지 않을까요 :

h = Hand() 
h[0] = 1 

다음 인터프리터는 또한 작업을 수행 할 __setitem__ 던더 방법에 액세스해야합니다.

이러한 메서드는 이미 내장 된 list 개체에 정의되어 있으므로 완벽하게 인덱싱 할 수 있습니다.
list 클래스에서 상속을 시도 할 수 있습니다. 그건 당신에게 달렸지 만, 예제는 다음과 같이 시작될 것입니다 :

class Hand(list): 
    ... 
+0

이것은 완벽하게 작동했습니다. 감사합니다! 이전에 "get_card"메서드를 만드는 것을 고려하고 있었지만, dunder 메서드는 잊어 버렸습니다. – macschmidt33

관련 문제