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