Python - 从包含类中值的列表中打印

时间:2018-04-05 23:24:21

标签: python

我正在尝试打印出名为Deck的变量值,它是使用类的值列表:

class Card:
      def __init__(self,suit,value):
        self.suit = suit
        self.value = value

Suits = ['Hearts','Spades','Clubs','Diamonds']
Values = ['2','3','4','5','6','7','8','9','10','J','Q','K','A']

Deck = [Card(suit,value) for suit in Suits for value in Values]

但每当我尝试打印时:

Deck = [Card(suit,value) for suit in Suits for value in Values]
print(Deck) 

它给了我:

<__main__.Card object at 0x054C7B10>

3 个答案:

答案 0 :(得分:1)

您的课程的印刷版本可以使用自定义__repr__方法覆盖:

class Card:

  def __init__(self,suit,value):
    self.suit = suit
    self.value = value

  def __repr__(self):
    return ' of '.join([self.value, self.suit])     


Suits = ['Hearts','Spades','Clubs','Diamonds']
Values = ['2','3','4','5','6','7','8','9','10','J','Q','K','A']

Deck = [Card(suit,value) for suit in Suits for value in Values]

print(Deck)

结果:

[2 of Hearts, 3 of Hearts, 4 of Hearts, 5 of Hearts, 6 of Hearts, 7 of Hearts, 8 of Hearts, 9 of Hearts, 10 of Hearts, J of Hearts, Q of Hearts, K of Hearts, A of Hearts, 2 of Spades, 3 of Spades, 4 of Spades, 5 of Spades, 6 of Spades, 7 of Spades, 8 of Spades, 9 of Spades, 10 of Spades, J of Spades, Q of Spades, K of Spades, A of Spades, 2 of Clubs, 3 of Clubs, 4 of Clubs, 5 of Clubs, 6 of Clubs, 7 of Clubs, 8 of Clubs, 9 of Clubs, 10 of Clubs, J of Clubs, Q of Clubs, K of Clubs, A of Clubs, 2 of Diamonds, 3 of Diamonds, 4 of Diamonds, 5 of Diamonds, 6 of Diamonds, 7 of Diamonds, 8 of Diamonds, 9 of Diamonds, 10 of Diamonds, J of Diamonds, Q of Diamonds, K of Diamonds, A of Diamonds]

答案 1 :(得分:1)

当要求print函数打印对象时,该输出是文本。因此,如果对象本身不是文本,print需要该对象的一些文本表示。

您可以明确地执行此操作 - 例如,通过一些显式函数调用来获取文本字符串 - 或隐式地,使用魔术方法进行文本表示。

显式选项的一个示例:

for item in collection:
    text = "The {0.denominator} of {0.suit}".format(item)
    print("{0}\n".format(text))

请参阅Python documentation for text formatting

为类定义字符串表示方法的示例:

class Card:

    ...

    def __str__(self):
        text = "The {0.denominator} of {0.suit}".format(self)
        return text

    def __repr__(self):
        text = "<Card: {0.denominator} of {0.suit}>".format(self)
        return text

for item in collection:
    print(item)

请参阅Python文档,了解神奇的__str____repr__文本表示方法。

答案 2 :(得分:0)

尝试使用namedtuple,它有人类的代表:

import collections as ct


suits = "♠ ♣ ♥ ♦".split()
ranks = "2 3 4 5 6 7 8 9 10 J Q K A".split()

Card = ct.namedtuple("Card", "suit rank")
deck = [Card(suit, rank) for suit in suits for rank in ranks]

print(deck)
# [Card(suit='♠', rank='2'), Card(suit='♠', rank='3'), , ...]