Python repr() Method Tutorial

While developing applications different types of objects are used in Python programming language. In some cases, we may need to print these objects into the screen or standard output. Even there are different functions like print() it is mainly created for basic types. In order to print more complex type objects like class etc. repr() method is used.

repr() Method Syntax

repr() method has very simple syntax where the object we want to print is provided as parameter.

repr( obj )
  • obj is the object we want to print to the console or standard output. It is required and can be a class, integer, string, etc.

Print Basic Types/Variables with repr() Method

We will start with simple examples where the repr() method can be used to print basic types and variable

obj = "wisetut.com"

num = 12

lst = [ 1 , 2 , 3 ]


repr(obj)

repr(num)

repr(lst)

Print Object with repr() Method

Even repr() method can be used for printing complex objects and values the representation should be defined inside these objects or classes. __repr()__ function is used to provide presentation of the object. When an object is called with the repr() method directly the __repr()__ function will be called. The __repr()__ function accepts the object itself as parameter in order to access object properties.

class Color:
   name = 'Red'
   def __repr__(self):
      return repr(self.name)


print( repr( Color() ) )

c1 = Color()

c1.name = "Yellow"

print( repr( c1 ) )
Print Object with repr() Method

Leave a Comment