数组不能正确打印Python

时间:2017-10-31 11:02:45

标签: python arrays list

class Item:
    def __init__(self, name, cost):
        self.name = name
        self.cost = cost


charm = Item("Charm of Capitalism", 20)
talis = Item("Talisman of Truth", 100)
shopArray = [charm, talis]

print("Items for sale: {}" .format(shopArray))

当我打印shopArray时,输出是

Items for sale: [<__main__.Item object at 0x02174270>, <__main__.Item object at 0x021742B0>]

我想让它显示shopArray中的项目

非常感谢任何帮助

2 个答案:

答案 0 :(得分:1)

class Item:
    def __init__(self, name, cost):
        self.name = name
        self.cost = cost

    def __repr__(self):
        return "name: " + self.name + " cost: " + str(self.cost)


charm = Item("Charm of Capitalism", 20)
talis = Item("Talisman of Truth", 100)
shopArray = [charm, talis]

print("Items for sale: {}" .format(shopArray))

您可以使用__repr__定义对象的外观。 我希望它能解决你的问题。

答案 1 :(得分:0)

据我所知,__repr__应该返回一个字符串,可以将其计算为实例化等效对象的代码。出于阅读目的,您应该使用Item.__str__方法:

class Item:
    def __init__(self, name, cost):
        self.name = name
        self.cost = cost

    def __str__(self):
        # Whichever formating you want.
        return '%s: %f' % (self.name, self.cost)


charm = Item("Charm of Capitalism", 20)
talis = Item("Talisman of Truth", 100)
shopArray = [charm, talis]

print("Items for sale: {}" .format(map(str, shopArray)))

请注意,您需要将Items列表映射到strs