2017-03-27 98 views
1

每當我想顯示我的卡,它給我錯誤。我想顯示我的卡的列表,但我得到了錯誤

我想將它顯示爲列表。

class Card: 
    suits = ["H", "D", "C", "S"] 
    values = ["2","3","4","5","6","7","8","9","T","J","Q","K","A"] 
    def __init__(self, value, suit): 
    self.value, self.suit = value, suit 
    def __str__(self): 
    return self.values[self.value] + " of " + self.suits[self.suit] 

class Deck: 
    def __init__(self): 
     self.decks = [] 
     for x in range(13): 
     for y in range(4): 
      self.decks.append(Cards(x, y)) 
    def __str__(self): 
     return self.decks 

    def printcard(self): 
     print self.decks 

def main(): 
    n=Deck() 
    n.printcard() 

Output: 
    [<__main__.Card instance at 0x0000000002694388>, <__main__.Card instance at 
    0x00000000026944C8>, <__main__.Card instance at 0x0000000002697C08>, 
    <__main__.Card instance at 0x0000000002697C48>, <__main__.Card instance at 
    0x0000000002697C88>, <__main__.Card instance at 0x0000000002697CC8>] 
+0

你必須定義你的'Card'類的表示。 –

回答

0

打印self.decks打印出Cards對象的列表。

既然你沒有定義__repr__方法爲您Cards對象(__str__方法只用於轉換爲string有用,但表示對象的list當不使用轉換爲字符串,將只對print(self.decks[0])工作),您只需獲取默認表示法:對象地址。

既然你沒有提供你Cards類,我創建了一個實體模型與定義的適當__repr__

class Card: 
    suits = ["H", "D", "C", "S"] 
    values = ["2","3","4","5","6","7","8","9","T","J","Q","K","A"] 
    def __init__(self, value, suit): 
    self.value, self.suit = value, suit 
    def __repr__(self): 
    return self.values[self.value] + " of " + self.suits[self.suit] 

class Deck: 
    def __init__(self): 
     self.decks = [] 
     for x in range(13): 
     for y in range(4): 
      self.decks.append(Card(x, y)) 

    def printcard(self): 
     print(self.decks) 

n=Deck() 
n.printcard() 

現在我得到這樣的結果,符合市場預期:

[2 of H, 2 of D, 2 of C, 2 of S, 3 of H, 3 of D, 3 of C, 3 of S, 4 of H, 4 of D, 4 of C, 4 of S, 5 of H, 5 of D, 5 of C, 5 of S, 6 of H, 6 of D, 6 of C, 6 of S, 7 of H, 7 of D, 7 of C, 7 of S, 8 of H, 8 of D, 8 of C, 8 of S, 9 of H, 9 of D, 9 of C, 9 of S, T of H, T of D, T of C, T of S, J of H, J of D, J of C, J of S, Q of H, Q of D, Q of C, Q of S, K of H, K of D, K of C, K of S, A of H, A of D, A of C, A of S] 
+0

我已經更新了我的代碼。感謝您的幫助。 –

+0

現在沒關係,我已經顯示了我的甲板列表,謝謝:) –

+0

看起來像一個新的問題。也許你可以編輯你的問題來添加它(使用編輯:標題)? (更準確,因爲它的寬度) –

相關問題