And I thought to myself what's the difference? Why not just be consistent and use str() or repr()?
So, I went back to read the Python documentation for the two functions and it states:
object.__repr__(self): called by the repr() built-in function and by string conversions (reverse quotes) to compute the “official” string representation of an object.object.__str__(self): called by the str() build-in function and by the print statement to compute the “informal” string representation of an object.I was still scratching my head after reading this. What did they mean by "official" and "informal"?
Digging into it further, I finally got the distinction!
For example, if we create a datetime object:
>>> import datetime
>>> today = datetime.datetime.now()
Using the str() function to display today gives this:>>> str(today)
'2013-11-08 15:06:15.063764'
While the repr() function gives this output:>>> repr(today)
'datetime.datetime(2013, 11, 8, 15, 6, 15, 63764)'
As shown above, the str() function displayed the date and time in a way that is easily read and understood. The repr() also returned a string, but was shown as the "official" representation of a datetime object, and when called by eval(), should return the same object.So, the __str__ (the "informal' representation) may be preferred for cases like this as it is simpler and easier to read.
However, even though the official representation of an object is a bit of an eyesore compared to the informal one, it is unambiguous(more comprehensive info about the object) and more robust against bugs!
So ending this post off, when to use which?
Well, every class you implement should always have a __repr__ method.
And if you think it'd be beneficial, you can also implement a __str__ method.
And one more thing! The print statement (along with the str() built-in function) also uses __str__ to display the string representation of the object!
Anyway, if you were wondering the same thing, I hope that clarified the difference between the two! :)