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中的项目
非常感谢任何帮助
答案 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
。