此代码生成52张牌。在这段代码中,我不明白为什么他/她使用Deck类a
方法中的b
类在self.deck
列表中附加参数Card
和__init__
? ??
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
class Card():
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
def __repr__(self):
return self.rank + " of " + self.suit
class Deck():
def __init__(self):
self.deck = []
for a in suits:
for b in ranks:
self.deck.append(Card(a, b))
def __repr__(self):
deck_comp = ''
for card in self.deck:
deck_comp += "\n "+card.__repr__()
return "The deck has: " + deck_comp
deck = Deck()
print(deck)
答案 0 :(得分:0)
变量名称对您没有帮助。代码在suits
和ranks
上迭代以获取它们的所有组合,Card
将创建一个具有2个参数的新实例:西服和等级
Hearts Two
Hearts Three
Hearts Four
...
Diamonds Two
Diamonds Three
Diamonds Four
...
使用有意义的名称,您将无法使用印刷品更好地理解:
def __init__(self):
self.deck = []
for suit in suits:
print(suit) # for understanding only
for rank in ranks:
print(suit, rank) # for understanding only
self.deck.append(Card(suit, rank))
这对应于两个列表之间的itertools.product
,您可以映射到Card
实例并保留列表
def __init__(self):
self.deck = list(map(lambda x: Card(*x), product(suits, ranks)))