python - 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?
解决方案
在一个方法内,return
只能执行一次,然后控制权返回到调用代码,所以你不能有一个return
内部循环。一种解决方案是构建要打印的整个字符串,然后将其返回。
如果您将课堂上的代码更改Deck
为:
def __str__(self):
return "\n".join(f"{card.rank} of {card.suit}" for card in self.deck)
它将返回一个包含整副纸牌的字符串,以便您的打印功能正常。
推荐阅读
- r - 访问嵌套列表中的数据框
- php - 显示数据库中的图像?
- python - 我如何在python中打印没有\ n的文本文件
- flutter - Flutter - 如何在材质应用程序中调用多个构建器项目?
- php - 如何使用 cURL 和 PHP 从使用 SSL 的网站获取数据?
- flutter - 我想在一个容器中显示 ListView,它的大小随着列表项的增加而动态增加
- iis - 按 Header 值列出的 IIS 白名单
- marklogic - 有没有办法在 MarkLogic 中以优化的方式为所有数据库安排备份?
- python - python子进程函数找不到路径:php文件
- time-complexity - 动态规划中记忆递归与表法的时间复杂度比较