- Trending Categories
- Data Structure
- Operating System
- C Programming
- 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.
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
This gives the output
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.
- What does the str() function do in Python Object Oriented Programming?
- What does the cmp() function do in Python Object Oriented Programming?
- Object Oriented Programming in Python?
- What is object-oriented programming (OOP)?
- What is Data Hiding in Python Object Oriented Programming?
- What is the difference between Object oriented programming and Object based programming?
- What are basic Object oriented programming concepts?
- Object Oriented language v/s Procedure oriented programming language.
- Differences between Procedural and Object Oriented Programming.
- What does reload() function do in Python?
- What does raw_input() function do in python?
- What does input() function do in python?
- What does print() function do in Python?
- What does open() function do in Python?