0

Python prints memory location instead of list. My code:

import random

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

    def show_card(self):
        print(self.value, self.suit)

    def get_value(self):
        if self.value > 10:
            return 10
        return int(self.value)

class Deck:
    def __init__(self):
        self.cards = []
        self.build()

    def build(self):
        for suit in ["♣", "♦", "♥", "♠"]:
            for value in range(2, 15):
                self.cards.append(Card(suit, value))
        return self.cards

    def shuffle_deck(self):
        random.shuffle(self.cards)
        return self.cards

Deck().build()
deck = Deck().shuffle_deck()
print(deck)

The problem is when I append "Card" object to "cards" list. How could I print "cards" list elements instead of memory locations?

themm1
  • 137
  • 2
  • 10

2 Answers2

1

It could be achieved through __repr__ magic method. Add this method:

def __repr__(self):
    return f'{self.value} {self.suit}'

into your Card class.

ilov3
  • 427
  • 2
  • 7
0

Just add a repr function to the card class

class Card:
    # your implementation
    def __repr__(self):
        return f'({self.value},{self.suit})'
adir abargil
  • 5,495
  • 3
  • 19
  • 29