2017-03-27 100 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

看起来像一个新的问题。也许你可以编辑你的问题来添加它(使用编辑:标题)? (更准确,因为它的宽度) –

相关问题