0
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))

When I print the shopArray the output is

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

I want it to display what items are in the shopArray

Any help would be much appreciated

2 Answers2

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))

You can define how you want your object look like using __repr__. I hope it resolves your question.

khelwood
  • 46,621
  • 12
  • 59
  • 83
Mahesh Karia
  • 1,930
  • 1
  • 10
  • 21
0

As far as I understood, __repr__ should return an string that can be evaluated into code that instantiates an equivalent object. For reading purposes, you should use the Item.__str__ method:

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)))

Notice that you need to map the list of Items to strs.

ldavid
  • 2,353
  • 2
  • 19
  • 37