__str__() 帮助 python 3
__str__() help python 3
我在 self.deck
列表中附加了所有可能的卡片,但是当我尝试使用字符串表示方法打印列表时,它给了我 <__main__.Deck object at 0x00238148>
我不知道为什么!我的代码在下面,如果有人可以查看它并告诉我如何在 class Deck
?
中获取所有 card
,我将不胜感激
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
class Card():
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
def __str__(self):
return 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 card
deck = Deck()
print(deck)
__str__
方法应该总是 return 字符串。在你的卡片 class 中,__str__
的 return 类型是正确的,但在 Deck class 中你正在 returning 卡片对象而不是你应该调用字符串__str__
方法中卡片对象的表示。
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 str(card)
return
returns 函数后面的值,结束函数。你只能从一个函数中 return 一次。您的 __str__
函数应该 return 一个字符串,并且它应该包含该字符串中您想要的所有内容。你可以遍历你的套牌并添加到一个字符串:
s = ''
for card in self.deck:
s += str(card) + ', '
但是你必须处理末尾的额外逗号。但是没有必要重新发明轮子。 Python 中的列表可以用 str()
转换为字符串,所以
str(self.deck)
会像
'[Two of Hearts, Three of Hearts, ... ]'
如果想要更灵活,可以使用字符串的join
方法,可以取一个列表:
'; '.join(self.deck)
类似于
'Two of Hearts; Three of Hearts; ...'
我在 self.deck
列表中附加了所有可能的卡片,但是当我尝试使用字符串表示方法打印列表时,它给了我 <__main__.Deck object at 0x00238148>
我不知道为什么!我的代码在下面,如果有人可以查看它并告诉我如何在 class Deck
?
card
,我将不胜感激
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
class Card():
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
def __str__(self):
return 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 card
deck = Deck()
print(deck)
__str__
方法应该总是 return 字符串。在你的卡片 class 中,__str__
的 return 类型是正确的,但在 Deck class 中你正在 returning 卡片对象而不是你应该调用字符串__str__
方法中卡片对象的表示。
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 str(card)
return
returns 函数后面的值,结束函数。你只能从一个函数中 return 一次。您的 __str__
函数应该 return 一个字符串,并且它应该包含该字符串中您想要的所有内容。你可以遍历你的套牌并添加到一个字符串:
s = ''
for card in self.deck:
s += str(card) + ', '
但是你必须处理末尾的额外逗号。但是没有必要重新发明轮子。 Python 中的列表可以用 str()
转换为字符串,所以
str(self.deck)
会像
'[Two of Hearts, Three of Hearts, ... ]'
如果想要更灵活,可以使用字符串的join
方法,可以取一个列表:
'; '.join(self.deck)
类似于
'Two of Hearts; Three of Hearts; ...'