繁体   English   中英

Python __str __()创建错误

[英]Python __str__() creating error

这是代码

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()时,如何输出手牌中的牌列表。

您的__str__方法必须返回一个值。 它没有(它只是打印)。

您可以执行以下操作:

def __str__(self):
    return '\n'.join(str(card) for card in self.hand)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM