0

Say I have an Element class

class Element(object):
    def __init__(self,key,val):
        self.key = key
        self.val = val

    def __str__(self):
        return '(' + str(self.key) + ',' + str(self.val) + ')'

Now when I try to print an array that contains objects of the Element class

arr = [Element(10,20),Element(20,30)]
print(arr)

, the output is -

[<maxheap.Element object at 0x01C1FCB0>, <maxheap.Element object at 0x01C270B0>]

Which function is printing <maxheap.Element object at 0x01C1FCB0>? Why isn't the __str__(self) method called as in print(Element(10,20))?

Ulrich Eckhardt
  • 662
  • 6
  • 14
Kakaji
  • 1,421
  • 2
  • 15
  • 23
  • 1
    Possible duplicate of [Difference between \_\_str\_\_ and \_\_repr\_\_ in Python](http://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python) – mkrieger1 Feb 18 '17 at 22:35

2 Answers2

0

Try using indexes instead of printing the list at once, like this:
print(arr[0])
print(arr[1])


Instead Of:
print(arr)

EDIT:
Using __repr__ works in this case.

  • But why? Using __repr(self)__ solves the issue meaning that print() calls repr(). I don't understand the use of __str(self)__ then. – Kakaji Feb 20 '17 at 18:28
  • @Kakaji Than please read the documentation. It's very clear/detailed there and on this network a real FAQ – frlan Feb 20 '17 at 19:06
-1

Try using

def __repr__(self):

instead of

def __str__(self):
piezzoritro
  • 141
  • 2
  • 14