+

What the repr () function does in OOP Python

The official Python documentation says that __repr __ () is used to compute the "official" string representation of an object. The built-in repr () function uses __repr __ () to display an object. __repr __ () returns a printable representation of an object, one way to create this object. __repr __ () is more useful for developers and __str __ () 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


< ins class = "adsbygoogle" style = "display: inline-block; width: 336px; height: 280px" data-ad-client = "ca-pub -6959883099270890 "data-ad-slot =" 6928654010 ">

 Point (x = 3 , y = 4 ) 

Let`s look at another example of using the repr () function and create a datetime object:


 & gt; & gt; & gt; import datetime & gt; & gt; & gt; today = datetime.datetime.now () 

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

 & gt ; & gt; & gt; 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 the datetime object which means that with this "official" string representation we can reverse engineer the object:

 & gt; & gt; & gt; eval (`datetime.datetime (2012, 3, 14, 9, 21, 58, 130922)`) datetime.datetime (2012, 3, 14, 9, 21, 58, 130922) 

Built-in function eval () takes a string and converts it to a datetime object.



Get Solution for free from DataCamp guru