2013-02-15 36 views
2

这可能是一个基本问题,因为我开始学习与书Think Python自学。有一个练习,我不安静,为什么不打印卡串,而是打印内存地址。打印给我一个班级列表上的内存地址而不是特定的STR

这里是整个代码:

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 

让我解释一下:

我调用该方法deal_hands与甲板Ĵ(J =甲板())和_cards = 2和手= 3。结果是一个Hand的列表,但是当我打印这个列表时,我按列表的方式获得了列表,但是却以丑陋的内存地址作为元素。为什么会发生这种情况,以及如何解决这个问题?

str应该用手也对吧?

回答

3

要获取列表以打印除实例信息之外的其他内容,您需要在Card类上实现__repr__。列表容器使用此函数而不是__str__来获取它所包含对象的字符串表示形式。这主要是为了调试目的,并且应该唯一标识该对象。

所以...首先,我在卡片类中添加了以下内容。

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模块,因为它希望得到复杂结构的不错输出蟒蛇时很方便。尝试在我上面嵌套的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]] 
相关问题