【问题标题】:How to print deck of cards in human readable way using Python如何使用 Python 以人类可读的方式打印纸牌
【发布时间】:2020-02-13 21:08:23
【问题描述】:

我正在创建一副卡片作为列表,需要打印出卡片。但是,当我尝试打印卡片组时,它会返回对象 ID 而不是可读的东西。

注意,这里的代码不完整。 Deck 类应该输入一个花色并返回该花色的卡片 2、3、4、5、6、7、8、9、10、J、Q、K、A。默认应返回完整的 52 张牌。但是,我还没有想出一种方法来默认所有的西装。目前默认保存为黑桃作为占位符。

我尝试过使用 strrepr 函数,但似乎没有什么不同。我尝试实现 repr 函数也没有出错,所以我假设我没有弄乱语法或任何东西。

from random import shuffle

# possible errors
class Error(Exception):
   """Base class for other exceptions"""
   pass
class RankError(Error):
    """Raised when input rank is not a valid card rank"""
    pass
class SuitError(Error):
   """Raised when input rank is not a valid card suit"""
   pass
class NoCardsError(Error):
    """Raised when deck does not have enough cards to deal"""
    pass

all_rank = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]
all_suit = ["♠", "♥", "♦", "♣"] 
hand = []

class PlayingCard:
    def __init__(self, rank, suit):
        if str(rank) not in all_rank:
            raise RankError("Invalid rank! Rank must be 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K, or A")
        if suit not in all_suit:
            raise SuitError("Invalid suit! Suit must be ♠, ♥, ♦, or ♣")
        self.rank = rank
        self.suit = suit
    def __str__(self):
        return str(self.rank) + " of " + str(self.suit)

class Deck:
    def __init__(self, suit = "♠"): # current default is spades, need to think of way to make default all the suits
        self.cards = [PlayingCard(rank, suit) for rank in all_rank]

    def __repr__(self):
        return "%r of %r" % (self.rank, self.suit)

    def shuffle_deck():
        self.shuffled_cards = random.shuffle(self.cards)

    def deal_card(card_count):
        if card_count > len(cards):
            raise NoCardsError("Not enough cards in the deck to deal.")
        else:
            hand = hand.append(cards.pop())
            return hand


deck1 = Deck()
print(deck1.cards)

我希望列表输出看起来像

[2 of ♠, 3 of ♠, 4 of ♠, 5 of ♠, 6 of ♠, etc.]

但实际输出是

[ma​​in.PlayingCard 对象位于 0x000001BE6C17EDD8>,ma​​in.PlayingCard 对象位于 0x000001BE6C17EB38>,ma​​in.PlayingCard 对象位于 0x000001BE6C17E748 >, ma​​in.PlayingCard 对象在 0x000001BE6C17E198>, ma​​in.PlayingCard 对象在 0x000001BE6C17E400>, ma​​in.PlayingCard 对象在 0x000001BE6C17E6A0>, ma​​in.PlayingCard 对象位于 0x000001BE6C17EE80>,ma​​in.PlayingCard 对象位于 0x000001BE6C17E470>,ma​​in.PlayingCard 对象位于 0x000001BE6C17E320>,ma​​in.PlayingCard 对象在 0x000001BE6C17EEB8>,ma​​in.PlayingCard 对象在 0x000001BE6C17E160>,ma​​in.PlayingCard 对象在 0x000001BE6C17E358>, main.PlayingCard 对象位于 0x000001BE6C17EF98>]

【问题讨论】:

  • 也只是字符串格式化的一个提示,str.format 通常比使用% 操作符更易读,更易于维护。这在 python2 和 python3 中都存在。在 python3.6+ 上,还有 f-strings,IMO 更好。

标签: python class repr


【解决方案1】:

要打印发现奇怪的对象符号,请尝试将 __repr__ 定义放在 PlayingCard 类中

例如:

class PlayingCard:
    def __init__(self, rank, suit):
        if str(rank) not in all_rank:
            raise RankError("Invalid rank! Rank must be 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K, or A")
        if suit not in all_suit:
            raise SuitError("Invalid suit! Suit must be ♠, ♥, ♦, or ♣")
        self.rank = rank
        self.suit = suit
    def __str__(self):
        return str(self.rank) + " of " + str(self.suit)

    # ADDITION HERE
    def __repr__(self):
        return "%r of %r" % (self.rank, self.suit)

所以运行print(deck1.cards)会输出

['2' of '♠', '3' of '♠', '4' of '♠', '5' of '♠', '6' of '♠', '7' of '♠', '8' of '♠', '9' of '♠', '10' of '♠', 'J' of '♠', 'Q' of '♠', 'K' of '♠', 'A' of '♠']

要打印整个卡片组,您需要更新Deck 类的__init__ 定义。

def __init__(self, suit = all_suit):
    self.cards = [PlayingCard(rank, one_suit) for rank in all_rank
                                              for one_suit in suit]

再次运行print(deck1.cards),它会打印出以下内容。

['2' of '♠', '2' of '♥', '2' of '♦', '2' of '♣', '3' of '♠', '3' of '♥', '3' of '♦', '3' of '♣', '4' of '♠', '4' of '♥', '4' of '♦', '4' of '♣', '5' of '♠', '5' of '♥', '5' of '♦', '5' of '♣', '6' of '♠', '6' of '♥', '6' of '♦', '6' of '♣', '7' of '♠', '7' of '♥', '7' of '♦', '7' of '♣', '8' of '♠', '8' of '♥', '8' of '♦', '8' of '♣', '9' of '♠', '9' of '♥', '9' of '♦', '9' of '♣', '10' of '♠', '10' of '♥', '10' of '♦', '10' of '♣', 'J' of '♠', 'J' of '♥', 'J' of '♦', 'J' of '♣', 'Q' of '♠', 'Q' of '♥', 'Q' of '♦', 'Q' of '♣', 'K' of '♠', 'K' of '♥', 'K' of '♦', 'K' of '♣', 'A' of '♠', 'A' of '♥', 'A' of '♦', 'A' of '♣']

并仔细检查我们有多少:

print(len(deck1.cards))  # 52

【讨论】:

  • 太棒了。谢谢! :)
  • @dumdum 太好了!另外,如果你有机会,也很高兴接受我的回答:) 谢谢stackoverflow.com/help/someone-answers
  • 已接受。作为后续问题,您对如何设置默认牌组以打印出所有 52 张牌的整个牌组有什么建议吗?问题出在文章顶部的注释之后。
猜你喜欢
  • 2012-03-19
  • 2021-10-23
  • 2016-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-02
  • 1970-01-01
相关资源
最近更新 更多