How to use repr() or str()


How to use repr() or str()

When you define __repr__ in your class and call repr() on object it will call __repr__ similarly for __str__ also.

 __repr__ and __str__ should not return anything other than string.

class Example:
   def __init__(self, x, y):
       self.x, self.y = x, y

   def __str__(self):
       return 'Str : Example obj (x=%s, y=%s)' % (self.x, self.y)

   def __repr__(self):
       return 'Repr : Example obj (x=%s, y=%s)' % (self.x, self.y)



eg_obj = Example(1,2)
print str(eg_obj)
print "--------------------------------"
print repr(eg_obj)

output :

Str : Example obj (x=1, y=2)
--------------------------------
Repr : Example obj (x=1, y=2)

If you don’t define __repr__ or __str__ the default string representation of object will be printed like <__main__.Example instance at 0xb775934c>


Read more about difference between __str__ and __repr__