使用另一个 class 在 class 的列表中追加参数?

append arguments in a list of a class using another class?

此代码生成 52 张牌。在此代码中,我不明白为什么 he/she 在 self.deck 列表中使用 Card class 在 [=21] 中附加参数 ab =] Deck __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) 

变量名帮不了你。代码遍历 suitsranks 以获得它们的所有组合,Card 是用 2 个参数创建一个新实例:suit 和 rank

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))

这对应于2个列表之间的一个itertools.product,你可以映射到一个Card实例并保留列表

def __init__(self):
    self.deck = list(map(lambda x: Card(*x), product(suits, ranks)))