运行文件时,我只能打印一张证卡有问题。它仅打印“黑桃二”。我希望打印整个甲板。不使用类时,打印没有问题。但是现在我正在尝试理解课程。谁能告诉我我在做什么错?我的下面的代码.....
RANKS = {2: "Two", 3: "Three", 4: "Four", 5: "Five", 6: "Six", 7: "Seven",
8: "Eight", 9: "Nine", 10: "Ten", 11: "Jack", 12: "Queen",
13: "King", 14: "Ace"}
SUITS = {1: "Spades", 2: "Clubs", 3: "Diamonds", 4: "Hearts"}
################################################
class Card():
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
def __str__(self):
return "%s of %s" %(self.rank, self.suit)
class Deck():
def __init__(self):
self.cards = []
for r in RANKS.values():
for s in SUITS.values():
self.cards.append(Card(r, s))
def __str__(self):
for i in self.cards:
return str(i)
deck = Deck()
print(deck)
答案 0 :(得分:3)
return
立即返回 。您需要将所有单独的卡字符串连接成一个字符串,然后返回 that 。
例如
def __str__(self):
return ', '.join([str(i) for i in self.cards])
答案 1 :(得分:0)
Deck上的str函数在循环的第一次迭代中返回,因此您只能得到一张卡。
def __str__(self):
cards = ''
for i in self.cards:
cards += str(i) + ' '
return cards.strip()
应该给所有卡片一个字符串