Using __repr__ or __str__ for own printable class?
Steven Taschuk
staschuk at telusplanet.net
Sat Apr 12 10:08:28 EDT 2003
Quoth Mads Orbesen Troest:
[...]
> Which is the most correct to use; or should I even overload both? The
> documentation says __str__ is for the, quote, informal representation;
> whereas __repr__ is for the, quote, official representation. Furthermore,
> __reptr__ should, quote, look like an expresseion. I'm not quite sure what
> is meant by these distinctions. Is it that __repr__ is used by pickle and
> the like, and - thus - should represent the entire object state? [...]
Pickle doesn't use __repr__; it has other, more reliable, ways of
getting object state.
__repr__ is used by: (1) '%r' % foo and repr(foo); (2) '%s' % foo,
str(foo), and print foo if __str__ isn't provided; and (3) the
interactive interpreter, when printing the value of an expression
entered at the prompt. (And no doubt, other places that I've
forgotten.)
The distinction is not a functional one; it is between different
kinds of information about the object which a string
representation might provide. The documentation in this case
means just what it says.
An example: The other day I described here an algorithm for
finding palindromes. The code I wrote to illustrate it has a
class which represents palindromes-in-progress; its __str__
representation is, for example,
'a man ... (pa)nama'
(Here 'a man' has matched 'nama', and the next step in building
the palindrome is to find a word or words starting with 'ap'.)
This is an informal, convenient representation. It is, as it
happens, suitable for display to an end user (say, in a status
message indicating what the palindrome search is looking at
presently).
The __repr__ representation, on the other hand, is
'NearPalindrome([['a', 'man'], ['panama']], 'pa', 0)'
This representation is nearly useless to an end user; but it gives
a complete account of the object and could be of use to a
programmer.
--
Steven Taschuk staschuk at telusplanet.net
"Its force is immeasurable. Even Computer cannot determine it."
-- _Space: 1999_ episode "Black Sun"
More information about the Python-list
mailing list