【问题标题】:Unable to print a class list attribute using instance of a class无法使用类的实例打印类列表属性
【发布时间】:2019-05-28 06:25:45
【问题描述】:

我正在设计一个具有 init() 方法的甲板类,最初有一个空列表。然后我将我的卡片附加到列表中。我正在尝试创建一个 x 实例并访问牌组的洗牌版本。我知道已经发布了许多解决方案。我只想用我的逻辑来理解我能够打印卡片元素的地址而不是卡片组本身。在尝试调试时,我不明白 print(x.cards_in_deck) 是在打印位置还是 x.shuffle...。Pycharm 调试的任何好的参考也将受到高度赞赏。

suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10,
         'Queen':10, 'King':10, 'Ace':11}
class Card:

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


    def __str__(self):
        return self.rank +' of '+self.suit
class Deck:

    def __init__(self):

        self.cards_in_deck = []
        for suit in suits:
            for rank in ranks:
                self.cards_in_deck.append(Card(suit, rank))
        #return self.cards_in_deck

    def __str__(self):
        # for card in Deck.cards_in_deck:
        #     return(card)
        return self.cards_in_deck

    def shuffle_cards(self):
        return random.shuffle(self.cards_in_deck)

x = Deck()
print(x.cards_in_deck,sep ='\n')
print(x.shuffle_cards(),sep = '\n')

【问题讨论】:

    标签: python python-3.x list class printing


    【解决方案1】:

    第一个打印语句将在您的 Deck 对象上打印实例变量“cards_in_deck”的值。变量的类型是一个列表,所以当它被打印出来时,它看起来像:

    [Two of Hearts, Three of Hearts, <more items>, King of Clubs, Ace of Clubs]
    

    第二个打印语句将调用 Deck 对象上的 shuffle_cards 方法,并打印该方法返回的任何内容。该方法返回在列表上调用 random.shuffle 的结果。该结果是一个新列表,即洗牌。

    现在,这些打印语句中的每一个都在打印一个列表对象,这就是上面的文本。如果您想打印每张单独的卡片,则需要循环遍历卡片,类似于初始化卡片组时循环遍历列表的方式。因此,您可以执行以下操作:

    for card in x.cards_in_deck:
        print(card)
    

    这会将每张卡片的名称打印在一个新的行上。

    编辑:我没有看到您在 Card 类中使用 __str__ 而不是 __repr__。打印列表时,Python 使用 __repr__ 方法来确定要在列表中的位置放置什么。见:Confused about __str__ on list in Python

    【讨论】:

    • 先生,我无法打印列表。它只是打印列表项的位置。
    • 我得到了这样的输出...[<__main__.card object at>, <__main__.card object at>
    • 是否有像 c 中的指针方法来捕获该地址并打印值,因为如果你说的是真的,那么我总是需要添加 __str__() 或 __repr__() 方法到上课!!!
    • 是否总是需要 __str__() 和 __repr__() 方法返回字符串类型来打印?如果不需要,那么我们可以创建自己的函数,将返回类型转换为函数(值)打印。为什么它们被特别称为 __str__() 和 __repr__()?如果你觉得很傻,请见谅,我是新手!!!
    • 你可能想错了。它仍在打印对象,而不是地址。但是,如果 __repr__ 没有在类上定义,它不知道应该使用文本来表示该对象。所以它最终只打印它所知道的:它是那个地址的 Card 对象。如果你正在创建一个你认为会被 print 调用的 Python 类,那么你应该在它上面实现 __repr__。
    【解决方案2】:

    如果您打印list,则list 中的任何项目都使用repr() 打印。您可以通过指定类的 __repr(self)__ 方法来定义使用的内容 - 您可能还想定义类的 __str__(self) 方法。如果您没有指定“特殊”reprstr,python 将为您创建默认的,可能无法打印 想要的内容。

    见:Difference between __str__ and __repr__?

    两者都应该返回一个字符串 - 你在 做什么,你会返回一个违反这些方法约定的 Deck 类的列表:

    独库:

    两个描述都说:

    返回值必须是字符串对象。

    并提供更多关于它们的信息。


    修复:

    suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
    ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
    values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10,
             'Queen':10, 'King':10, 'Ace':11}
    
    import random
    
    class Card:
        def __init__(self,suit,rank):
            self.suit = suit
            self.rank = rank
    
        def __str__(self):
            return self.rank +' of '+self.suit
        def __repr__(self):
            return self.rank +' of '+self.suit
    
    class Deck:
        def __init__(self):
            # always create shuffled decks
            self.create_new_deck()
    
        def __str__(self):  
            # return a string here, not a list
            # join only takes strings so you need to stringify each card beforehand
            return ', '.join(str(c) for c in self.cards_in_deck)        
    
        def __repr__(self):
            return ', '.join(str(c) for c in self.cards_in_deck)
    
        # create a new deck and shuffle it immediately
        def create_new_deck(self):
            self.cards_in_deck = [Card(s, r) for s in suits for r in ranks]
            random.shuffle(self.cards_in_deck)
    
    x = Deck()
    print(str(x)) 
    

    输出:

    King of Clubs, Ace of Diamonds, Seven of Spades, Ace of Spades, Three of Hearts, 
    Eight of Hearts, Five of Clubs, Four of Spades, King of Diamonds, Five of Hearts, 
    Eight of Spades, Three of Diamonds, Three of Spades, Six of Diamonds, 
    Eight of Diamonds, Queen of Hearts, Ace of Hearts, Ten of Clubs, Two of Diamonds, 
    Six of Clubs, King of Hearts, Seven of Clubs, Queen of Clubs, King of Spades, 
    Nine of Diamonds, Six of Hearts, Nine of Clubs, Queen of Diamonds, Queen of Spades,
     Ten of Diamonds, Seven of Hearts, Ten of Hearts, Eight of Clubs, Ace of Clubs,
    Jack of Clubs, Nine of Spades, Four of Diamonds, Seven of Diamonds, Nine of Hearts,
     Two of Clubs, Jack of Hearts, Jack of Spades, Jack of Diamonds, Two of Spades, 
    Ten of Spades, Four of Hearts, Three of Clubs, Six of Spades, Five of Spades, 
    Two of Hearts, Five of Diamonds, Four of Clubs
    

    调试:

    【讨论】:

      猜你喜欢
      • 2018-08-04
      • 1970-01-01
      • 2019-04-10
      • 2019-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多