我的列表打印出的是对象而不是值

2024-06-05 23:45:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个有一副卡片的程序,我想打印出我的列表中的值,我已经填充了52张卡片。卡片有两个变量,值都是整数。 问题是,在我的例子中,不是打印出黑桃的“A”,而是1取4(黑桃是4,A是值1),它打印对象<main。0x00000221CB653520处的卡对象>

到目前为止,我的代码是:

class Card:
def __init__(self, suit, value):
    assert 1 <= suit <= 4 and 1 <= value <= 13
    self.suit = suit
    self.value = value

def show(self):
    return "{} of {}".format(self.suit, self.value)



class CardDeck:
def __init__(self):
    # Constructs the Deck

    self.cards = []
    for s in range(1, 5):
        for v in range(1, 14):
            self.cards.append(Card(s, v))

    CardDeck.shuffle(self)
    for c in self.cards:
        c.show()

def shuffle(self):
    for i in range(len(self.cards) - 1, 0, -1):
        rnd = random.randint(0, i)
        self.cards[i], self.cards[rnd] = self.cards[rnd], self.cards[i]




Deck = CardDeck()
print(Deck.cards[1:-1]) <----- Should print the full list with both variables, suit and value

Tags: 对象inselfforvaluedefrangecard
2条回答

在不深入代码细节的情况下,如果您希望在从某个类调用对象时print方法执行其他操作,而不是打印类的名称和对象的内存位置,则需要在该类上实现magic方法__str__(self)。在您的例子中,我看到您有一个返回字符串表示的方法show,但没有一个方法__str__。它很可能与show方法非常相似。您可能还希望将这样的方法添加到CardDeck类中

顺便说一句,你的例子似乎受到了《如何像计算机科学家一样思考》一书的启发。如何使用__str__以及这个纸牌游戏例子的细节在那本书中都有很好的解释

打印值使用repr,因此您应该为自定义表示提供__repr__函数:

import random

# list of suits for number to text
suits = ["spades", "diamonds", "hearts", "clubs"]

class Card:
    def __init__(self, suit, value):
        assert 1 <= suit <= 4 and 1 <= value <= 13
        self.suit = suit
        self.value = value

    def __repr__(self):
        return "{} of {}".format(self.value, suits[self.suit - 1])

class CardDeck:
    def __init__(self):
        self.cards = []
        for s in range(1, 5):
            for v in range(1, 14):
                self.cards.append(Card(s, v))

        CardDeck.shuffle(self)

    def shuffle(self):
        for i in range(len(self.cards) - 1, 0, -1):
            rnd = random.randint(0, i)
            self.cards[i], self.cards[rnd] = self.cards[rnd], self.cards[i]

Deck = CardDeck()
print(Deck.cards[1:-1])

输出:

[8 of hearts, 4 of diamonds, 9 of spades, 2 of clubs, 1 of hearts, 3 of spades, 6 of spades, 3 of clubs, 7 of spades, 7 of hearts, 5 of hearts, 12 of clubs, 13 of clubs, 7 of diamonds, 9 of clubs, 1 of spades, 3 of hearts, 2 of hearts, 1 of clubs, 8 of spades, 12 of spades, 11 of diamonds, 3 of diamonds, 9 of hearts, 10 of spades, 5 of spades, 13 of hearts, 2 of diamonds, 5 of clubs, 5 of diamonds, 8 of clubs, 11 of hearts, 2 of spades, 6 of clubs, 7 of clubs, 11 of spades, 4 of hearts, 4 of spades, 9 of diamonds, 6 of diamonds, 12 of hearts, 6 of hearts, 4 of clubs, 10 of clubs, 13 of diamonds, 12 of diamonds, 13 of spades, 11 of clubs, 10 of hearts, 10 of diamonds]

相关问题 更多 >