Python - Class String Representation

Introduction

__repr__ method and __str__ method are run automatically every time an instance is converted to its print string.

Printing an object displays whatever is returned by the object's __str__ or __repr__ method, if the object either defines one itself or inherits one from a superclass.

Double-underscored names are inherited.

__str__ is preferred by print and str.

__repr__ is used as a fallback.

Coding just __repr__ alone suffices to give a single display in all cases-prints, nested appearances, and interactive echoes.

Demo

class Person: 
    def __init__(self, name, job=None, pay=0): 
        self.name = name #  w w w  .  j a v a 2s  . c  om
        self.job  = job 
        self.pay  = pay 
    def lastName(self): 
        return self.name.split()[-1] 
    def giveRaise(self, percent): 
        self.pay = int(self.pay * (1 + percent)) 
    def __repr__(self):                                        # Added method 
        return '[Person: %s, %s]' % (self.name, self.pay)      # String to print 

if __name__ == '__main__': 
    bob = Person('Bob Smith') 
    sue = Person('Sue Jones', job='dev', pay=100000) 
    print(bob) 
    print(sue) 
    print(bob.lastName(), sue.lastName()) 
    sue.giveRaise(.10) 
    print(sue)

Result