这里是代码
from robustCard import Card
import random
class Hand:
def __init__(self,numCardsInHand):
self.hand = list()
for x in range(0,numCardsInHand):
randVal = random.randint(1,13)
randKey = random.choice(['d','c','h','s'])
self.hand.append(Card(randVal,randKey))
def bjValue(self):
totalVal = 0
for x in range(0,len(self.hand)):
totalVal+=self.hand[x].bjValue()
return totalVal
def __str__(self):
for x in range(0,len(self.hand)):
print(self.hand[x])
if (__name__ == "__main__"):
hand = Hand(5)
print(hand)
这是我的卡片类 str ():
def __str__(self):
letterRank = self.rankList[self.rank-1]
letterSuit = self.suitDict[self.suit]
return "%s of %s" % (letterRank,letterSuit)
这是我的错误:
Four of clubs
Jack of clubs
nine of diamonds
Queen of clubs
Seven of clubs
Traceback (most recent call last):
File "/Users/bmassoumi/Documents/Web development/python_workspace/Python class/Hand.py", line 24, in <module>
print(hand)
TypeError: __str__ returned non-string (type NoneType)
当我有两个不同的 str()来处理时,如何输出手册中的牌列表。
答案 0 :(得分:2)
您的__str__
方法必须必须返回一个值。它没有(它只是打印)。
您可以执行以下操作:
def __str__(self):
return '\n'.join(str(card) for card in self.hand)