打印出存储在列表中的对象 [英] Print out objects stored in a list

查看:49
本文介绍了打印出存储在列表中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,正忙着制作二十一点游戏.我几乎可以正确打印出我的卡片组,但是似乎无法遍历列表中存储的所有卡片.

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)

输出并返回:

Two of hearts

打印输出:

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

所以我知道 str 的正确语法是使用return而不是打印.但是,如果我使用打印,那么我得到的正是我想要的,所有我的牌都在套牌中,除了以下错误: str 返回的非字符串(类型为NoneType).如果我使用return,这是正确的语法,那么当我打印纸牌时,所有打印出的就是第一张牌,即两张心.为什么会这样?

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?

推荐答案

在一个方法中, return 只能执行一次,然后控件返回到调用代码,因此您不能在循环内返回.一种解决方案是构建要打印的整个字符串,然后将其返回.

Within a method, return can only be executed once, then control returns to the calling code, so you can't have a return inside a loop. One solution is to build the entire string to be printed, then return that.

如果将类 Deck 中的代码更改为:

If you change your code in class Deck to:

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

它将返回一个包含整个卡片组的字符串,以便您的打印正常运行.

It will return a string containing the entire deck of cards so that your print functions correctly.

这篇关于打印出存储在列表中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆