简体   繁体   English

如何使用 Python 以人类可读的方式打印卡片组

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

I am creating a deck of cards as a list and need to print out the deck.我正在创建一副卡片作为列表,需要打印出卡片。 However, when I try to print the deck, it returns the object ID rather than something readable.但是,当我尝试打印卡片组时,它返回 object ID 而不是可读的。

Note, the code here is incomplete.注意,这里的代码是不完整的。 The Deck class should take in an input suit and return the cards 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K, A for that suit.甲板 class 应该接受输入花色并返回该花色的卡片 2、3、4、5、6、7、8、9、10、J、Q、K、A。 The default should return a full 52 card deck.默认应返回完整的 52 张牌。 However, I haven't figured out a way to make the default all of the suits yet.但是,我还没有想出一种方法来默认所有的西装。 Currently the default is saved as spades as a placeholder.目前默认保存为黑桃作为占位符。

I have tried using str and repr functions, but it doesn't seem to make a difference.我尝试过使用strrepr函数,但似乎没有什么不同。 I am also not getting an error from my attempted implementation of repr function, so I assume that I am not messing up the syntax or anything.我也没有从我尝试执行repr function 中得到错误,所以我假设我没有弄乱语法或任何东西。

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)

I expect a list output that looks like我希望列表 output 看起来像

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

but the actual output is但实际的 output 是

[< main .PlayingCard object at 0x000001BE6C17EDD8>, < main .PlayingCard object at 0x000001BE6C17EB38>, < main .PlayingCard object at 0x000001BE6C17E748>, < main .PlayingCard object at 0x000001BE6C17E198>, < main .PlayingCard object at 0x000001BE6C17E400>, < main .PlayingCard object at 0x000001BE6C17E6A0>, < main .PlayingCard object at 0x000001BE6C17EE80>, < main .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 ZA8CFDE6331BD59EB2AC96F8911C4B6 [< main .PlayingCard object at 0x000001BE6C17EDD8>, < main .PlayingCard object at 0x000001BE6C17EB38>, < main .PlayingCard object at 0x000001BE6C17E748>, < main .PlayingCard object at 0x000001BE6C17E198>, < main .PlayingCard object at 0x000001BE6C17E400>, < main .PlayingCard object at 0x000001BE6C17E6A0>, < main .PlayingCard object at 0x000001BE6C17EE80>, < main .PlayingCard object at 0x000001BE6C17E470>, < main .PlayingCard object at 0x000001BE6C17E320>, < main .PlayingCard object at 0x000001BE6C17EEB8>, < main .PlayingCard object at 0x000001BE6C17E160>, <.PlayingCard object at 0x000001BE6C17E358>, <.PlayingCard ZA8CFDE6331BD59EB2AC96F8911C4B6 66Z at 0x000001BE6C17EF98>] 66Z 在 0x000001BE6C17EF98>]

To print uncover the weird object notation, try putting the __repr__ definition in the PlayingCard class要打印发现奇怪的 object 符号,请尝试将__repr__定义放入扑克牌PlayingCard

For example:例如:

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)

So running print(deck1.cards) will output所以运行print(deck1.cards)将 output

['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 '♠']

To print the entire deck , you'll need to update the __init__ definition for the Deck class.要打印整个甲板,您需要更新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]

Running print(deck1.cards) again, it'll print out the following.再次运行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 '♣']

And to double check how many we have:并仔细检查我们有多少:

print(len(deck1.cards))  # 52

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM