【发布时间】:2020-09-13 23:53:09
【问题描述】:
我正在尝试使用类在 python 项目中打印玩家手。
(在经历了很多挫折之后,我用谷歌搜索了如何通过拆包来做到这一点)
有没有人能提供一个例子来说明我如何使用__repr__ 来简单地打印这个列表?而不是__init__ 可以换成__repr__ 吗?是否应该使用另一个函数来添加从类中打印列表的功能?
例如,为什么下面的解包可以工作,但没有解包就不行?
>>> print(*test_player.cards, sep='\n')
Ace of Clubs
King of Clubs
>>> print(test_player.cards)
[<__main__.Card object at 0x000001E2BA608388>, <__main__.Card object at 0x000001E2BA608488>]
我的代码主体如下:
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8,
'Nine':9, 'Ten':10, 'Jack':10, 'Queen':10, 'King':10, 'Ace':11}
class Card:
def __init__(self,suit,rank):
self.suit = suit
self.rank = rank
def __str__(self):
return self.rank + ' of ' + self.suit
class Deck:
def __init__(self):
self.deck = [] # start with an empty list
for suit in suits:
for rank in ranks:
self.deck.append(Card(suit,rank))
def __str__(self):
deck_comp = '' # start with an empty string
for card in self.deck:
deck_comp += '\n '+card.__str__() # add each Card object's print string
return 'The deck has:' + deck_comp
def shuffle(self):
random.shuffle(self.deck)
def deal(self):
single_card = self.deck.pop()
return single_card
class Hand:
def __init__(self):
self.cards = [] # start with an empty list as we did in the Deck class
self.value = 0 # start with zero value
self.aces = 0 # add an attribute to keep track of aces
def add_card(self,card):
self.cards.append(card)
self.value += values[card.rank]
test_player=Hand()
test_deck=Deck()
test_player.add_card(test_deck.deal())
test_player.add_card(test_deck.deal())
【问题讨论】:
-
列表中的项目将使用
__repr__打印,这就是您的第二个示例中发生的情况。如果你真的想改变这个,覆盖__repr__为Card。 (我不推荐它,因为它违背了打印列表的标准 Python 方式。相反,可能覆盖__str__为您打印卡片的Hand,或添加print_cards()函数到Hand) .