Python - String Representation: __repr__ and __str__


__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.


class adder: 
    def __init__(self, value=0): = value                    # Initialize data 
    def __add__(self, other): += other                   # Add other in place (bad form?) 
# from   w w w  . ja  va 2s  .  c o  m
x = adder()                                  # Default displays 

class addstr(adder): 
   def __str__(self):                       # __str__ but no __repr__ 
       return '[Value: %s]' %     # 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]' %     # User-friendly string 
   def __repr__(self): 
       return 'addboth(%s)' %     # As-code string 

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