Repr or Str ?

Bart Ogryczak B.Ogryczak at gmail.com
Tue Feb 6 05:57:43 EST 2007


On Feb 6, 11:47 am, "Johny" <pyt... at hope.cz> wrote:
> Where and when is good/nescessary to use `repr`  instead of `str` ?
> Can you please explain the differences
> Thanks

RTFM. http://docs.python.org/ref/customization.html

__repr__( self)
    Called by the repr() built-in function and by string conversions
(reverse quotes) to compute the ``official'' string representation of
an object. If at all possible, this should look like a valid Python
expression that could be used to recreate an object with the same
value (given an appropriate environment). If this is not possible, a
string of the form "<...some useful description...>" should be
returned. The return value must be a string object. If a class defines
__repr__() but not __str__(), then __repr__() is also used when an
``informal'' string representation of instances of that class is
required.

    This is typically used for debugging, so it is important that the
representation is information-rich and unambiguous.

__str__( self)
    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. The return value must be a string object.





More information about the Python-list mailing list