11. Building Useful Classes


Please any moderator could you give a more detailed explanation about the repr() function as the explantion given in the exercise is quite short. Though i have successfully completed the exercise but i am still eager to know what is the exact use of the repr() function and exactly where and how it should be used.
@gaurangtandon @appylpye


Hi @ronit1710 ,

When we define a class, we often would like to be able to represent the value of an instance of the that class as a meaningful string. We can specify such a representation for a class that we have created by defining a __repr__ method for that class. We can also specify a string representation for a class by defining a __str__ method for that class.

One example of a convenience that defining a string representation for a class provides for us is that we can output an informative string for an instance by using print, or when we perform some other action that requires a string representation of an object.

Without a __repr__ or __str__ method, we get something like this, if we print our Point3D instance ...

<Point3D object at 0x7f790ba46950>

That might not be very useful to us. By designing a __repr__ or __str__ method, we can output something like this, when we use print, which is much nicer ...

(1, 2, 3)

See Python: repr and str.

*** Last edited on July 8, 2016 to add details. ***


Thanks @appylpye Now i have properly understood the use of repr() function. :smile:


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.