我有一个有一副卡片的程序,我想打印出我的列表中的值,我已经填充了52张卡片。卡片有两个变量,值都是整数。 问题是,在我的例子中,不是打印出黑桃的“A”,而是1取4(黑桃是4,A是值1),它打印对象<main。0x00000221CB653520处的卡对象>强>
到目前为止,我的代码是:
class Card:
def __init__(self, suit, value):
assert 1 <= suit <= 4 and 1 <= value <= 13
self.suit = suit
self.value = value
def show(self):
return "{} of {}".format(self.suit, self.value)
class CardDeck:
def __init__(self):
# Constructs the Deck
self.cards = []
for s in range(1, 5):
for v in range(1, 14):
self.cards.append(Card(s, v))
CardDeck.shuffle(self)
for c in self.cards:
c.show()
def shuffle(self):
for i in range(len(self.cards) - 1, 0, -1):
rnd = random.randint(0, i)
self.cards[i], self.cards[rnd] = self.cards[rnd], self.cards[i]
Deck = CardDeck()
print(Deck.cards[1:-1]) <----- Should print the full list with both variables, suit and value
在不深入代码细节的情况下,如果您希望在从某个类调用对象时print方法执行其他操作,而不是打印类的名称和对象的内存位置,则需要在该类上实现magic方法
__str__(self)
。在您的例子中,我看到您有一个返回字符串表示的方法show
,但没有一个方法__str__
。它很可能与show
方法非常相似。您可能还希望将这样的方法添加到CardDeck
类中顺便说一句,你的例子似乎受到了《如何像计算机科学家一样思考》一书的启发。如何使用
__str__
以及这个纸牌游戏例子的细节在那本书中都有很好的解释打印值使用
repr
,因此您应该为自定义表示提供__repr__
函数:输出:
相关问题 更多 >
编程相关推荐