首页 > 解决方案 > Print out objects stored in a list

问题描述

I am new to Python, busy creating a blackjack game. I have almost got printing out my deck of cards right, but I can't seem to iterate through all the cards stored in the list.

suits = ['Hearts','Diamonds','Spades','Clubs']
ranks = ['Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack','Queen','King','Ace']
values = {'Two':2, 'Three':3,'Four':4,'Five':5,'Six':6,'Seven':7,'Eight':8,'Nine':9,'Ten':10,'Jack':10,'Queen':10,'King':10,'Ace':(1,11)}

playing = True

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

    def __str__(self):
        print(f"{self.rank} of {self.suit}")

class Deck:

    def __init__(self):
        self.deck = []
        for suit in suits:
            for rank in ranks:
                self.deck.append(Card(suit, rank))

    def __str__(self):
        for card in self.deck:
            return f"{card.rank} of {card.suit}"

deck = Deck()

print(deck)

Output with return:

Two of hearts

Output with print:

Two of Hearts
Three of Hearts
Four of Hearts
Five of Hearts
Six of Hearts
Seven of Hearts
Eight of Hearts
Nine of Hearts
Ten of Hearts
Jack of Hearts
Queen of Hearts
King of Hearts
Ace of Hearts etc...plus error

So I know the correct syntax for str is to use return and not print. But if I use print then I get exactly what I want, all my cards in the deck, except with this error: str returned non-string (type NoneType). If I use return, which is the correct syntax, then when I print my deck all that prints out is the first card, the two of hearts. Why is that?

标签: pythonlistloopsobject

解决方案


在一个方法内,return只能执行一次,然后控制权返回到调用代码,所以你不能有一个return内部循环。一种解决方案是构建要打印的整个字符串,然后将其返回。

如果您将课堂上的代码更改Deck为:

def __str__(self):
    return "\n".join(f"{card.rank} of {card.suit}" for card in self.deck)

它将返回一个包含整副纸牌的字符串,以便您的打印功能正常。


推荐阅读