![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.