这可能是一个基本问题,因为我开始用书Think Python学习自学。还有一个练习,我不安静,为什么不打印卡片串,而是打印一个内存地址。
以下是整个代码:
import random
class Card(object):
'''Represents a standard playing card'''
def __init__(self, suit=0, rank=2):
self.suit = suit
self.rank = rank
suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
rank_names = [None, 'Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King']
def __str__(self):
return '%s of %s' % (Card.rank_names[self.rank], Card.suit_names[self.suit])
def __cmp__(self, other):
t1= self.suit, self.rank
t2 = other.suit, other.rank
return cmp(t1, t2)
class Deck(object):
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 pop_card(self):
return self.cards.pop()
def add_card(self, card):
self.cards.append(card)
def shuffle(self):
random.shuffle(self.cards)
def sort(self):
self.cards.sort()
def move_card(self, hand, num):
for i in range(num):
hand.add_card(self.pop_card())
def deal_hands(self, _cards, hands):
handsdeal = []
for i in range(hands):
hand = Hand()
self.move_card(hand, _cards)
handsdeal.append(hand.cards)
return handsdeal
class Hand(Deck):
def __init__(self, label=''):
self.cards = []
self.label = label
让我解释一下:
我用deck j(j = Deck())和_cards = 2以及hands = 3调用方法deal_hands。结果是Hand的列表但是当我打印该列表时,我得到列表按预期列出但是丑陋的内存地址作为元素。为什么会发生这种情况?如何解决?
手也应该使用str ,对吧?
答案 0 :(得分:3)
要获取列表以打印除了在Card类上实现__repr__所需的实例信息之外的其他内容。列表容器使用此函数而不是__str__来获取其包含的对象的字符串表示形式。这主要用于调试目的,应该唯一标识对象。
所以......首先我将以下内容添加到您的Card类中。
def __repr__(self):
return '%s of %s' % (Card.rank_names[self.rank], Card.suit_names[self.suit])
然后我在文件底部使用以下内容生成输出。
# Printing the whole list (which uses __repr__)
j=Deck()
foo = j.deal_hands(2,3)
print foo
# Printing the lists (which uses __str__)
for hand in foo:
for card in hand:
print card
我的输出
$ python test.py
[[King of Spades, Queen of Spades], [Jack of Spades, 10 of Spades], [9 of Spades, 8 of Spades]]
King of Spades
Queen of Spades
Jack of Spades
10 of Spades
9 of Spades
8 of Spades
更新:刚认为它也值得一提pprint模块,因为它想要在python中获得复杂结构的良好输出时很方便。尝试在我上面的嵌套for循环下添加以下内容。
import pprint
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(foo)
输出
[ [King of Spades, Queen of Spades],
[Jack of Spades, 10 of Spades],
[9 of Spades, 8 of Spades]]