- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
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.
- Related Articles
- 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 Data Hiding in Python Object Oriented Programming?
- Python Object-oriented and Functional Programming
- What is object-oriented programming (OOP)?
- What is the difference between Object oriented programming and Object based programming?
- Object-Oriented Programming in R
- What are basic Object oriented programming concepts?
- Object Oriented language v/s Procedure oriented programming language.
- How to start object-oriented programming in C++?
- Differences between Procedural and Object Oriented Programming
- Object Oriented language v/s Object based programming language.
- What does reload() function do in Python?