【发布时间】:2019-05-08 07:04:49
【问题描述】:
class Deck:
def __init__(self):
self.cards=[]
for suit in range(4):
for rank in range(1,14):
card=Card( suit, rank )
self.cards.append(card)
def __str__ (self):
res=[]
for card in self.cards:
res.append(str(card))
return '\n'.join(res)
def pick_card(self):
from random import shuffle
shuffle(self.cards)
return self.cards.pop()
def add_card(self,card):
if isinstance(card, Card): #check if card belongs to card Class!!
self.cards.append(card)
def move_cards(self, gen_hand, num):
for i in range(num):
gen_hand.add_card(self.pick_card())
class Hand(Deck):
def __init__(self, label=''):
self.cards = []
self.label = label
def __str__(self):
return 'The {} is composed by {}'.format(self.label, self.cards)
mazzo_uno = Decks()
hand = Hand('New Hand')
mazzo_uno.move_cards(hand, 5)
print(hand)
我正在尝试学习面向对象的编程。当我尝试从子类 Hand() 打印对象 hand 时遇到了这个问题。我在 0x10bd9f978> 打印了类似 main.Card 对象,而不是 self.cards 列表中 5 张卡片的正确字符串名称:
The New Hand is composed by [<__main__.Card object at 0x10bd9f978>,
<__main__.Card object at 0x10bd9fd30>, <__main__.Card object at 0x10bd9fe80>,
<__main__.Card object at 0x10bcce0b8>, <__main__.Card object at 0x10bd9fac8>]
我也尝试这样做以将 self.cards 转换为字符串,但我得到了"TypeError: sequence item 0: expected str instance, Card found"。
def __str__(self):
hand_tostr = ', '.join(self.cards)
return 'The {} is composed by {}'.format(self.label, hand_tostr)
我在本网站上阅读了应该使用 __repr__ 的其他答案,但我不明白如何在 Hand 类中添加它。
【问题讨论】:
-
为你的班级添加
__str__Card,这样你就可以使用 str(card) 来获取字符串类型
标签: python string class oop methods