Home > OS >  How to iterate through a list object inside a class object
How to iterate through a list object inside a class object

Time:10-12

I'm working on writing a script to play Blackjack and can't resolve a defect I encountered tonight. Basically, I'm trying to iterate through a list object that exists within a class. I can always get it to print the first card (i.e. the Five of Hearts), but not the remaining two in my test case.

Here's the relevant code:

class Card:

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

    def __str__(self):
        return self.rank   " of "   self.suit

class Play_Pile:

    def __init__(self,pile_owner):
        self.pile_owner = pile_owner
        self.pile_cards = []
        self.pile_state = "NORM"

    def add_card(self,new_card):
        self.pile_cards.append(new_card)

    #THE FIRST IF STATEMENT AND ITS FOR LOOP ARE DEFECTIVE IN THE CONTEXT OF THE TEST CASE
    def __str__(self):
        if self.pile_owner == "HUMAN":
            for card in self.pile_cards:
                return card.rank   " of "   card.suit   "\n"
        elif self.pile_owner == "COMPY":
            return self.pile_cards[0].rank   " of "   self.pile_cards[0].suit

Here's the Unittest test case:

#module references
import unittest
import blackjack

class PlayPile_Display_Test(unittest.TestCase):
        playpile_instance = blackjack.Play_Pile("HUMAN")

        card_1 = blackjack.Card("Hearts", "Five")
        card_2 = blackjack.Card("Spades", "Five")
        card_3 = blackjack.Card("Spades", "Ace")

        playpile_instance.add_card(card_1)
        playpile_instance.add_card(card_2)
        playpile_instance.add_card(card_3)

        print(playpile_instance)

if __name__ == '__main__':
    unittest.main(verbosity = 2)

Let me know what I'm missing about lists and how to iterate through them within a class?

CodePudding user response:

You iterate over the list, but immidietly you return the value. You need to accumulate the string and then return the result.

str = ""
for card in self.pile_cards:
    str  = card.rank   " of "   card.suit   "\n"
return str

CodePudding user response:

You need to accumulate the string you build for each card, but also use the Card.__str__ you defined, instead of writing again the Card representation logic (X of Y)

def __str__(self):
    if self.pile_owner == "HUMAN":
        result = ""
        for card in self.pile_cards:
            result  = str(card)   "\n"
        return result
    elif self.pile_owner == "COMPY":
        return str(self.pile_cards[0])

You can do it nicely with a "\n".join too

def __str__(self):
    if self.pile_owner == "HUMAN":
        return "\n".join(map(str, self.pile_cards))
    elif self.pile_owner == "COMPY":
        return str(self.pile_cards[0])
  • Related