What does the repr() function do in Python Object Oriented Programming?


The official Python documentation says __repr__() is used to compute the “official” string representation of an object. The repr() built-in function uses __repr__() to display the object. __repr__()  returns a printable representation of the object, one of the ways possible to create this object.  __repr__() is more useful for developers while __str__() is for end users.

Example

The following code shows how __repr__() is used.

class Point:

   def __init__(self, x, y):

     self.x, self.y = x, y

   def __repr__(self):

     return 'Point(x=%s, y=%s)' % (self.x, self.y)

p = Point(3, 4)

print p

Output

This gives the output

Point(x=3, y=4)

Lets consider another example of use of repr() function and create a datetime object −

>>> import datetime
>>> today = datetime.datetime.now()

When I use the built-in function repr() to display today −

>>> repr(today)
'datetime.datetime(2012, 3, 14, 9, 21, 58, 130922)'

We can see that this returned a string but this string is the “official” representation of a datetime object which means that using this “official” string representation we can reconstruct the object −

>>> eval('datetime.datetime(2012, 3, 14, 9, 21, 58, 130922)')
datetime.datetime(2012, 3, 14, 9, 21, 58, 130922)

The eval() built-in function accepts a string and converts it to a datetime object.

Updated on: 15-Jun-2020

541 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements