Using __repr__ or __str__ for own printable class?

Donn Cave donn at u.washington.edu
Fri Apr 25 19:38:05 EDT 2003


Quoth Steven Taschuk <staschuk at telusplanet.net>:
...
| I've submitted a documentation patch for the __str__ and __repr__
| docs, following ideas discussed in this thread:
|     <http://www.python.org/sf/727789>
| I solicit comments.  (The __repr__ blurb is much the same as that
| in the previous post; I've fiddled more extensively with the
| __str__ blurb.)

I still think that the normal usage of __str__ can be directly
described as a data conversion to type string.  I know you don't
find that completely illuminating on its own, but I think it does
convey an essential idea that is otherwise likely to be missed.
See for example the __str__ and __repr__ definitions in Cookie.py.
Since this apparently isn't as obvious to you as it is to me, you
may be in a better position to explain it if I can convince you
that there's something to it.  If we can decide on some central
notion behind normal __str__ usage, the examples will make more
sense and it won't be necessary to describe __str__ as "not __repr__".

	Donn Cave, donn at u.washington.edu
----------------------------------------
| __str__(self)
|
|     Called by the str() built-in function and by the print statement
|     to compute a string representation of an object.  The return value
|     must be a string object.
|
|     This differs from __repr__() in that it does not specifically
|     serve the purpose of providing a programmer with detailed
|     information about the object; it may provide a string
|     representation of the object for other purposes, as appropriate to
|     the object.  Such purposes include display to an application
|     end-user, reference in an application log for administrators, or
|     providing a string to other code which requires one -- in general,
|     purposes for which the programmer-oriented information of
|     __repr__() is not appropriate.




More information about the Python-list mailing list