Search code examples
pythonblackjack

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


This code generate 52 deck of cards. Here in this code I didn't understand why he/she appends arguments a and b in self.deck list using Card class in class Deck __init__ method???

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) 

Solution

  • The name of the variables doesn't help you. The code iterate over the suits and the ranks to get all combination of them, the Card is to create a new instance with the 2 param : suit and rank

    Hearts Two
    Hearts Three
    Hearts Four
    ...
    Diamonds Two
    Diamonds Three
    Diamonds Four
    ...
    

    Use meaningfull names, and you can't use a print to understand better :

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

    This correspond to a itertools.product between the 2 lists, you can map to a Card instance and keep the list

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