__str__ vs. __repr__
dgobbi at hickory.irus.rri.on.ca
Mon Nov 1 15:43:27 EST 1999
Gerrit Holl <gerrit.holl at pobox.com> wrote:
> Randall Hopper wrote:
>> 1) Is there a convention for what __str__ and __repr__ should return for
> __str__ should return a string, __repr__ may also return, for example, a
The Python Language Reference Manual has a few lines on this subject,
specifically in Section 3.3.1.
Called by the repr() built-in function and by string conversions
(reverse quotes) to compute the "official" string representation
of an object. This should normally look like a valid Python
expression that can be used to recreate an object with the same
value. By convention, objects which cannot be trivially converted
to strings which can be used to create a similar object produce a
string of the form "<...some useful description...>".
Called by the str() built-in function and by the print statement
to compute the "informal" string representation of an object.
This differs from __repr__() in that it does not have to be a valid
Python expression: a more convenient or concise representation may
be used instead.
In short: no they are not the same, yes you can define them both. If you
don't define __str__(), then str(object) will default to
>> 2) Or, whatever they return, should they return the same value?
> I don't know: I think it's wrong to use both.
> linuxgames.nl.linux.org All about games on Linux in Dutch (under construction).
> www.nl.linux.org The Dutch resource for Dutch Linux documentation.
> www.nl.linux.org/discoverb Learn foreign words and definitions.
> www.nl.linux.org/~gerrit/asperger I'm an Asperger, go here for more info.
> www.nl.linux.org/~gerrit About me and pictures of me.
--David Gobbi, MSc dgobbi at irus.rri.on.ca
Advanced Imaging Research Group
Robarts Research Institute, University of Western Ontario
More information about the Python-list