Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to properly define a return string within a for loop for a Class using OOP in Python

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading