0

I have this code to generate a list that contains a deck of Cards object instances:

import random
class Cards:

    def __init__(self, Value = random.choice([1,2,3,4,5,6,7,8,9,10,11,12,13]), Group = random.choice(["Diamonds", "Hearts", "Clubs", "Spades"])):
        self.Value = Value
        self.Group = Group

    def printCards(self):
        if self.Value == 11:
            print("J de " + self.Group)
        elif self.Value == 12:
            print("Queen de " + self.Group)
        elif self.Value == 13:
            print("King de " + self.Group)
        else:
            print(str(self.Value) + " de " + self.Group)

def creat_deck():
    list_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
    list_groups = ["Diamonds", "Hearts", "Clubs", "Spades"]
    list_deck = []
    for number in list_numbers:
        for group in list_groups:
            list_deck.append(Cards(number, group))
    return list_deck

when I do a print I get this:

print(creat_deck())

    [<__main__.Cards object at 0x02D3D100>, <__main__.Cards object at 0x02D3D070>, <__main__.Cards object at 0x02D3DC70>, ...and so on until the Card object 52]

What can I do to get the actual cards like:

 [Queen of Diamonds, 7 of Clubs, , ...and so on]
  • 1
    `Cards` class needs a `__repr__` and/or `__str__` method, which returns a desired string. – hpaulj Aug 08 '20 at 02:39

1 Answers1

4

You'll want to implement __repr__ and __str__ on Cards:

def __str__(self):
    return f"{self.Value} of {self.Group}"

def __repr__(self):
    return f'{type(self).__name__}({self.Value!r}, {self.Group!r})'

More information is at Difference between __str__ and __repr__? and on the Python docs

Edit: updated based on comments.

Josh
  • 136
  • 6
  • 2
    once you have `__repr__` -- `__str__` will call it by default – Azat Ibrakov Aug 08 '20 at 02:50
  • 2
    `__repr__` should show the object's construction if possible, so that would be `return f'{type(self).__name__}({self.Value!r}, {self.Group!r})'`. What you have for `__repr__` would make a good `__str__` though. – wjandrea Aug 08 '20 at 03:34