Python - String Representation: __repr__ and __str__

Introduction

__str__ is tried first for the print operation and the str built-in function. It generally should return a user-friendly display.

__repr__ is used in all other contexts: for interactive echoes, the repr function, and nested appearances, as well as by print and str if no __str__ is present.

__repr__ is used everywhere, except by print and str when a __str__ is defined.

You can code a __repr__ to define a single display format used everywhere, and may code a __str__ to either support print and str exclusively.

Demo

class adder: 
    def __init__(self, value=0): 
        self.data = value                    # Initialize data 
    def __add__(self, other): 
        self.data += other                   # Add other in place (bad form?) 
# w  w w.j  av a2 s .com
x = adder()                                  # Default displays 
print(x) 


class addstr(adder): 
   def __str__(self):                       # __str__ but no __repr__ 
       return '[Value: %s]' % self.data     # Convert to nice string 

x = addstr(3) 
print( x + 1 ) 
print( x )                                          # Default __repr__ 
print(x)                                     # Runs __str__ 
print( str(x), repr(x) )

class addboth(adder): 
   def __str__(self): 
       return '[Value: %s]' % self.data     # User-friendly string 
   def __repr__(self): 
       return 'addboth(%s)' % self.data     # As-code string 

x = addboth(4) 
print( x + 1 )
print( x )                                          # Runs __repr__ 
print(x)                                     # Runs __str__ 
print( str(x), repr(x) )

Result