Home > Software engineering >  How do I print out the stack of cards?
How do I print out the stack of cards?

Time:11-19

Problem

I am learning Python on Udemy and wanted to print out the card deck created in the following script.

Reprex

import random 

suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 
            'Nine':9, 'Ten':10, 'Jack':11, 'Queen':12, 'King':13, 'Ace':14}

class Card:
    
    def __init__(self,suit,rank):
        self.suit = suit
        self.rank = rank
        self.value = values[rank]
        
    def __str__(self):
        return self.rank   ' of '   self.suit

class Deck:
    
    def __init__(self):
        # Note this only happens once upon creation of a new Deck
        self.all_cards = [] 
        for suit in suits:
            for rank in ranks:
                # This assumes the Card class has already been defined!
                self.all_cards.append(Card(suit,rank))
    
    def shuffle(self):
        # Note this doesn't return anything
        random.shuffle(self.all_cards)
        
    def deal_one(self):
        # Note we remove one card from the list of all_cards
        return self.all_cards.pop()        

Works

The above works when I want to pick out a single card.

print(Deck().all_cards[0])

#Two of Hearts

Error

Yet, it does not work when I try to print out the whole deck (or just enter it).

print(Deck().all_cards)

#[<__main__.Card object at 0x0000028F128D1700>, <__main__.Card object at 0x0000028F128D1280>, #<__main__.Card object at 0x0000028F128D1730>, <__main__.Card object at 0x0000028F128D1D60>,
#...
#...
#<__main__.Card object at 0x0000028F128D9C40>, <__main__.Card object at 0x0000028F128D9C70>]

Attempts

I tried to add a print line to the script, but that didn't work. Any help would be appreciated.

CodePudding user response:

Add __repr__ to your Card class:

class Card:
    
    def __init__(self,suit,rank):
        self.suit = suit
        self.rank = rank
        self.value = values[rank]
        
    def __str__(self):
        return self.rank   ' of '   self.suit

   def __repr__(self):
        return str(self)   # return the same thing as `__str__`
  • Related