how to use __str__ and __repr__?
peter at engcorp.com
Tue Jun 8 02:47:58 CEST 2004
Jim Newton wrote:
> i read that in the documenation. and i assumed from that that
> print another()
> actually prints the string returned from another().__str__()
> and thus __str__ must be being inherited from the superclass
> of another, but apparently print does something different.
> why does print another() actually print something rather than
> complaining that there is no __str__ defined?
I believe print basically calls str(obj) on the object, and
str() is a builtin which (I believe) basically tries to call
__str__() and if that is not defined, calls __repr__(). If
__repr__ is not defined, it probably defers to a standard
representation based on the id() of the object, which is
Not sure what else you're trying to do (I haven't read your
full post) but I believe this and some thought should answer
for pretty much everything you're seeing.
Note that you should probably never call __str__() directly,
but call the str() builtin instead. Same for __repr__()
versus the repr() builtin.
More information about the Python-list