class Card:
def __init__(self, suit, value):
self.suit = suit
self.value = value
def show(self):
# print(f"{self.value} of {self.suit}")
return (self.suit, self.value)
class Deck(Card):
"""
Deck is collection of 52 cards.
"""
colour = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
rank = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
def __init__(self):
d = []
for s in Deck.colour:
for r in Deck.rank:
c = Card(s,r)
d.append(c)
self.pack = d
def draw(self):
return self.pack.pop()
mydeck = Deck()
j =1
for i in mydeck.pack:
print(j, "t", mydeck.draw().show(), " count remaining ", len(mydeck.pack))
j +=1
在尝试打印mydeck.deck
的内容时,这是一个列表,它只打印总值的一半。如果再次运行,它将打印下半个值。
请帮我弄清楚为什么所有内容都没有打印?
我是初学者,非常感谢任何反馈。 提前谢谢。
我以这种方式修复了:
class Card:
def __init__(self, suit, value):
self.suit = suit
self.value = value
def show(self):
# print(f"{self.value} of {self.suit}")
return (self.suit, self.value)
class Deck():
"""
Deck is collection of 52 cards.
"""
colour = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
rank = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
def __init__(self):
d = []
for s in Deck.colour:
for r in Deck.rank:
c = Card(s,r)
d.append(c)
self.pack = d
def draw(self):
return self.pack.pop()
mydeck = Deck()
j =1
breakpoint()
for i in mydeck.pack:
print(j, "t", i.show(), " count remaining ", len(mydeck.pack)-j)
j +=1
输出
1 ('Hearts', 'Two') count remaining 51
2 ('Hearts', 'Three') count remaining 50
3 ('Hearts', 'Four') count remaining 49
4 ('Hearts', 'Five') count remaining 48
5 ('Hearts', 'Six') count remaining 47
6 ('Hearts', 'Seven') count remaining 46
7 ('Hearts', 'Eight') count remaining 45
8 ('Hearts', 'Nine') count remaining 44
9 ('Hearts', 'Ten') count remaining 43
10 ('Hearts', 'Jack') count remaining 42
......................
只是不要在循环中调用 draw(( —i
已经在迭代 mydeck.pack 中的每个卡,所以你可以调用i.show()
。您可能希望将i
重命名为card
。
正如Ed Ward在评论中指出的那样,你也绝对不希望Deck继承Card。