【发布时间】:2022-01-11 01:01:38
【问题描述】:
所以我试图在 python 中创建一个二十一点游戏,但我收到一个我不知道如何解决的类型错误。我为卡片创建了一个类,可以让我轻松打印出单张卡片的名称,但我也希望能够打印卡片组内卡片的名称。为此,我想我会使用我在 Card 类中使用的字符串方法。
import random
symbols = ('Spades','Diamonds','Hearts',"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':11, 'Queen':12, 'King':13, 'Ace':14}
playing = True
class Card:
def __init__(self,symbol=0,rank=0):
self.rank = ranks
self.symbol = symbol
value = values [rank]
def __str__(self):
return self.rank + "of" + self.symbol
class Deck:
def __init__(self):
self.deck = [] # start with an empty list
for symbol in symbols:
for rank in ranks:
self.deck.append(Card(symbol,rank)) # build Card objects,add to list
def __str__(self):
deck_comp = '' # start with an empty string
for Card in self.deck:
deck_comp += '\n'+ Card.__str__() # add each Card object's print string
return 'The deck has:' + deck_comp
def shuffle(self):
random.shuffle(self.deck)
def deal(self):
single_card = self.deck.pop()
return single_card
test_deck = Deck()
print(test_deck)
这是我收到的错误消息。我知道 Card.str() 可能保存为元组,但我该如何解决这个问题?
错误:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-41-1bfc314b8e70> in <module>
1 test_deck = Deck()
----> 2 print(test_deck)
<ipython-input-40-36ad41485748> in __str__(self)
10 deck_comp = '' # start with an empty string
11 for Card in self.deck:
---> 12 deck_comp += '\n' + Card.__str__() # add each Card object's print string
13 return 'The deck has:' + deck_comp
14
<ipython-input-31-543b708a921e> in __str__(self)
7
8 def __str__(self):
----> 9 return self.rank + "of" + self.symbol
TypeError: can only concatenate tuple (not "str") to tuple
【问题讨论】:
标签: python oop types concatenation