Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I have this code to generate the list that contains the 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 try to display 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]

help me to get the actual cards like format as below:

 [Queen of Diamonds, 7 of Clubs, , ...and so on]

1 Answer

0 votes
by (36.8k points)

You have 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})'

 Improve your knowledge in data science from scratch using Data science online courses

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...