__str__ method on list of objects

You just need to replace the __str__ method of the PlayingCard class with a __repr__ method:

class PlayingCard():

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

    def __repr__(self):
        return '{} of {}'.format(Value(self.value).name, Suit(self.suit).name)

Alternatively you can change the __str__ method in the Deck class to get the string representation of every card:

class Deck():

    def __init__(self):
        self.cards=[PlayingCard(val,suit) for val in Value for suit in Suit]

    def __str__(self):
        return str([str(card) for card in self.cards])

Then you get the correct output with:

...

deck = Deck()
print(deck)

Output:
(The 2nd way will add quotes around every printed card)

[Two of Spades, Two of Hearts, Two of Clubs, Two of Diamonds, Three of Spades, Three of Hearts, Three of Clubs, Three of Diamonds, Four of Spades, Four of Hearts, Four of Clubs, Four of Diamonds, Five of Spades, Five of Hearts, Five of Clubs, Five of Diamonds, Six of Spades, Six of Hearts, Six of Clubs, Six of Diamonds, Seven of Spades, Seven ofHearts, Seven of Clubs, Seven of Diamonds, Eight of Spades, Eight of Hearts, Eight of Clubs, Eight of Diamonds, Nine of Spades, Nine of Hearts, Nine of Clubs, Nine of Diamonds, Ten of Spades, Ten of Hearts, Ten of Clubs, Ten of Diamonds, Jack of Spades, Jack of Hearts, Jack of Clubs, Jack of Diamonds, Queen of Spades, Queen of Hearts, Queen of Clubs, Queen of Diamonds, King of Spades, King of Hearts, King of Clubs, King of Diamonds, Ace of Spades, Ace of Hearts, Ace of Clubs, Ace of Diamonds]

When you call __str__ on a list object, it will go through every element of the list and call __repr__ on that object to get its representation.

So when you call print(deck), you get:

--> deck.__str__()
--> str(self.cards)
--> [card.__repr__() for card in self.cards]

Tags:

Python