Tutorial Study Image

Python repr()

The built-in function repr() is used to return the printable representation of the given object. The returning output will be in a string.


repr(obj) #where obj can be a string
 

repr() Parameters:

Takes single parameter. In many object types and most builtins that eval(repr(obj))=obj). The eval() function evaluates the expression given as its arguments.

Parameter Description Required / Optional
obj  the object whose printable representation has to be returned Required

repr() Return Value

Actually, repr()function calls __repr__() of the given object.We can  __repr__() so that repr() works differently.

Input Return Value
 obj string representation

Examples of repr() method in Python

Example 1: How repr() works in Python?


var = 'foo'

print(repr(var))
 

Output:

'foo'

Example 2:Implement __repr__() for custom objects


class Person:
    name = 'Adam'

    def __repr__(self):
        return repr('Hello ' + self.name )

print(repr(Person()))
 

Output:

'Hello Adam'

Example 3: Working With Class Objects


class Color:
       color='orange'
       def __repr__(self):
              return repr(self.color)
 o=Color()
 repr(o)
 

Output:

“‘orange'”