[Python] Why is Card(suit, rank) passed as a parameter in self.cards.append()? What does it do?

Discussão em 'Python' iniciado por Stack, Maio 2, 2025.

  1. Stack

    Stack Membro Participativo

    class Card:
    def __init__(self,suit,rank):
    self.suit=suit
    self.rank=rank

    def __str__(self) -> str:
    return f"{self.rank['rank']} of {self.suit}"

    class Deck:

    def __init__(self):

    self.cards=[]
    suits=['spades','clubs','hearts','diamonds']
    ranks=[
    {"rank": "A","value":11},
    {"rank":"2","value":2},
    {"rank":"3","value":3},
    {"rank":"4","value":4},
    {"rank":"5","value":5},
    {"rank":"6","value":6},
    {"rank":"7","value":7},
    {"rank":"8","value":8},
    {"rank":"9","value":9},
    {"rank":"10","value":10},
    {"rank":"J","value":10},
    {"rank":"Q","value":10},
    {"rank":"K","value":10}

    ]

    for suit in suits:
    for rank in ranks:
    self.cards.append(Card(suit,rank))


    I'm trying to understand this line of code in the context of a Deck and Card class in Python:self.cards.append(Card(suit, rank))

    I don't understand what Card(suit, rank) is doing inside the append(). What exactly is being appended to the list? And why pass it this way?

    Also, would it be better to move this card-creation logic into a separate method instead of putting it inside init()?

    Continue reading...

Compartilhe esta Página