I want to create a card deck using OOP in Python. I have two classes, Card and Deck, and I want to print all cards in a deck. However, I am not sure how to handle this problem because I can print the values (or rather return a string) in the Card class, in the Deck class and using __str__() or another method (showCard()
). I am convinced the proper way to print all cards in the deck us by accessing a method in the Card class. I think the best way to do this is to utilize the __str__() method in Card, but all examples I found define a new print method (such as showCard()
).
The issue is that the proper way of printing in OOP is by returning a string. However, this fails when I use the for loop to loop over all suits and values.
Code:
import random
class Deck:
SUITS = ['Clubs', 'Spades', 'Hearts', 'Diamonds']
VALUES = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
def __init__(self):
self.deck = []
self.createADeck()
def createADeck(self):
for value in self.VALUES:
for suit in self.SUITS:
self.deck.append(Card(suit, value))
def shuffle(self):
random.shuffle(self.deck)
def __str__(self):
for card in self.deck:
card.__str__() # I DON'T KNOW WHAT TO PUT HERE
class Card:
def __init__(self, suit, value):
self.suit = suit
self.value = value
def showCard(self):
print(f"The {self.value} of {self.suit}")
def __str__(self):
return f"The {self.value} of {self.suit}"
>Solution :
You need to assemble the entire string in the loop, and return it only after the loop is finished. This can be done in multiple ways, e.g.
def __str__(self):
s = ""
for card in self.deck:
s += str(card)
s += "\n"
return s
or
def __str__(self):
return "\n".join(str(card) for card in self.deck)