【发布时间】:2020-02-13 21:08:23
【问题描述】:
我正在创建一副卡片作为列表,需要打印出卡片。但是,当我尝试打印卡片组时,它会返回对象 ID 而不是可读的东西。
注意,这里的代码不完整。 Deck 类应该输入一个花色并返回该花色的卡片 2、3、4、5、6、7、8、9、10、J、Q、K、A。默认应返回完整的 52 张牌。但是,我还没有想出一种方法来默认所有的西装。目前默认保存为黑桃作为占位符。
我尝试过使用 str 和 repr 函数,但似乎没有什么不同。我尝试实现 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.]
但实际输出是
[main.PlayingCard 对象位于 0x000001BE6C17EDD8>,main.PlayingCard 对象位于 0x000001BE6C17EB38>,main.PlayingCard 对象位于 0x000001BE6C17E748 >, main.PlayingCard 对象在 0x000001BE6C17E198>, main.PlayingCard 对象在 0x000001BE6C17E400>, main.PlayingCard 对象在 0x000001BE6C17E6A0>, main.PlayingCard 对象位于 0x000001BE6C17EE80>,main.PlayingCard 对象位于 0x000001BE6C17E470>,main.PlayingCard 对象位于 0x000001BE6C17E320>,main.PlayingCard 对象在 0x000001BE6C17EEB8>,main.PlayingCard 对象在 0x000001BE6C17E160>,main.PlayingCard 对象在 0x000001BE6C17E358>, main.PlayingCard 对象位于 0x000001BE6C17EF98>]
【问题讨论】:
-
也只是字符串格式化的一个提示,
str.format通常比使用%操作符更易读,更易于维护。这在 python2 和 python3 中都存在。在 python3.6+ 上,还有 f-strings,IMO 更好。