如何使用 Python 以人类可读的方式打印一副纸牌

How to print deck of cards in human readable way using Python

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

注意,这里的代码不完整。牌组 class 应该接受输入花色和 return 该花色的牌 2、3、4、5、6、7、8、9、10、J、Q、K、A。默认应该 return 一副完整的 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 的 ♠,3 的 ♠,4 的 ♠ 的 5,6 的 ♠,等等]

但实际输出是

[<main.PlayingCard 对象在 0x000001BE6C17EDD8>, <main.PlayingCard 对象在 0x000001BE6C17EB38>, < main.PlayingCard object at 0x000001BE6C17E748>, <main.PlayingCard object at 0x000001BE6C17E198>, <main.PlayingCard object at 0x000001BE6C17E400> , <main.PlayingCard 对象在 0x000001BE6C17E6A0>, <main.PlayingCard 对象在 0x000001BE6C17EE80>, <main[=42= .PlayingCard object at 0x000001BE6C17E470>, <main.PlayingCard object at 0x000001BE6C17E320>, <main.PlayingCard object at 0x000001BE6C17EEB8>, <main.PlayingCard object at 0x000001BE6C17E160>, <main.PlayingCard object at 0x000001BE6C17E358>, <main.PlayingCard object at 0x000001BE6C17EF98>]

要打印 uncover the weird object notation, try put the __repr__ definition in the PlayingCard class

例如:

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 class 的 __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