(很抱歉,如果这个问题有点含糊,我不确定标题会更好)
我不确定当您获得类似于以下内容的称呼时是什么:
[<< strong>主要。卡片对象位于0x00350490>,<< strong>主要。卡片对象位于0x00350590>] [<< strong> main .Card对象位于0x00350510>,<< strong> main .Card对象位于0x003501B0>]
但是我正在尝试打印出更具可读性的格式。我想确保事情顺序正确,然后再进一步更改顺序。
import random as rd
class Card:
card_rank = [str(n) for n in range(2, 10)]
card_rank.extend(['Ten', 'Jack', 'Queen', 'King', 'Ace'])
card_suit = ['Spades', 'Clubs', 'Diamonds', 'Hearts']
def __init__(self, rank, suit):
assert 2 <= rank <= 14 and 1 <= suit <= 4
self.rank = rank
self.suit = suit
def __str__(self):
return '{} of {}'.format(Card.card_rank[self.rank - 2], Card.card_suit[self.suit - 1])
class Deck:
def __init__(self):
self.cards = [Card(rank, suit) for rank in range(2, 14 + 1) for suit in range(1, 4 + 1)]
class Player:
def __init__(self):
self.hand = []
def build_hand(self, card):
self.hand.append(card)
def __str__(self):
return self.hand
class Dealer(Deck, Player):
def deck_shuffle(self):
rd.shuffle(self.cards)
def deck_deal(self):
single_card = self.cards.pop()
print(single_card)
return single_card
dealer = Dealer()
player_hand = Player()
dealer_hand = Player()
dealer.deck_shuffle()
player_hand.build_hand(dealer.deck_deal())
dealer_hand.build_hand(dealer.deck_deal())
player_hand.build_hand(dealer.deck_deal())
dealer_hand.build_hand(dealer.deck_deal())
print(player_hand.hand)
print(dealer_hand.hand)
我很确定这是我自己应该能够实现的非常明显的事情,但是反复试验只会导致错误。我正在做的是什么导致无法读取的格式?为什么str()或 str 在这里不起作用?
答案 0 :(得分:1)
列表的__str__
方法不会对列表中的元素进行递归调用str
;它仅使用__repr__
。如果要更好地显示手,请自己生成:
print(" ".join([str(c) for c in player_hand.hand))
print(" ".join([str(c) for c in dealer_hand.hand))