如何在列表中创建对象的字符串表示形式?

时间:2018-08-23 23:09:57

标签: python python-3.x class multiple-instances

我正在尝试使用Python创建一个Kings Cup游戏(涉及纸牌的饮料游戏)。就目前而言,当我打印会议录和参与者列表时,似乎控制台已打印出内存地址。我将不胜感激任何帮助,指示,提示,建议。请,谢谢。

import random

class Participant:
    def __init__(self, name, gender):
        self.name = name
        self.gender = gender
        self.cards = []
    def drawCard(self):
        self.cards += deck.pop()
    def showCards(self):
        print(self.name) 
        print(self.cards) 


class Card:
    def __init__(self, value, suite):
        self.value = value
        self.suite = suite
    def getValue(self):
        return self.value
    def getSuite(self):
        return self.suite
    def __str__(self):
        return ("{0} of {1}".format(self.value, self.suite))

deck = []
participants = []

def shuffleDeck():
    for suite in ["Clubs", "Diamonds", "Hearts", "Spades"]:
        for num in ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]:
        deck.append(Card(num, suite))
    random.shuffle(deck)
    return deck 


players = input("Enter the number of players: ")
numPlayers = int(players)
if numPlayers < 3:
    print(players)
    print("Not enough players.")
elif numPlayers > 12:
    print(players)
    print("That's too many players.")
else:
    for player in range(numPlayers):
        player += 1
        name = input("Player %s's Name: " %player) 
        gender = input("Player %s's Gender: " %player)
        participants.append(Participant(name, gender))

deck = shuffleDeck()

print(deck)
print(participants)

2 个答案:

答案 0 :(得分:4)

为每个实例定义一个表示形式。例如:

class Card:
    def __init__(self, value, suite):
        self.value = value
        self.suite = suite
    def getValue(self):
        return self.value
    def getSuite(self):
        return self.suite
    def __str__(self):
        return ("{0} of {1}".format(self.value, self.suite))
    def __repr__(self):
        return ("{0} of {1}".format(self.value, self.suite))

然后

>> a = [Card(3,'Diamonds'),Card(2,'Spades')]
>> print(a)
[3 of Diamonds, 2 of Spades]

也就是说,请参阅@abarnerts有关格式化repr的评论

答案 1 :(得分:1)

Python使用指针将信息存储在内存中。创建变量时,您会说:嘿,python,请记住,此变量指向此内存。

当您打印字符串或数字时,python会自动为您设置格式,但是当涉及到更复杂的对象时,它不知道该怎么做。

要通知python该怎么做,您需要创建已经完成的魔术函数__str__(每边2个下划线)。

问题是,当您打印列表时,您不会打印每个单独的对象,而是打印每个对象的列表代表。这样更有用,因为您不是在存储简单的对象(如字符串或整数),而是存储复杂且已定义的结构

要告诉python 表示,您需要创建魔术函数__repr__。我强烈建议您不要复制__str__函数。最好打印类似Card(*value*, *suite*)的东西。换句话说:您的init函数。

礼品代码:

def __repr__(self):
    return '{}({}, {})'.format(self.__name__, self.value, self.suite)