2

这可能是一个基本问题,因为我是从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

让我解释:

我用甲板 j (j = Deck()) 和 _cards= 2 和 hands= 3 调用方法 deal_hands。结果是 Hand 的列表,但是当我打印该列表时,我得到的列表与预期的一样,但内存地址丑陋作为元素。为什么会发生这种情况,如何解决?

str也应该被 Hand 使用,对吧?

4

1 回答 1

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]]
于 2013-02-15T02:46:00.530 回答