Default printing behavior for classes
Charles G Waldman
cgw at fnal.gov
Thu Jun 24 14:03:26 EDT 1999
You're looking for the __repr__ and/or __str__ methods:
>From the docs:
__repr__ (self)
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...>".
__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.
Note that these methods should *return* the string value, not print
it.
If c is a class instance, and the class has __repr__ or __str__
methods, these will be invoked when you say "print c".
If you have both a __str__ method and a __repr__ method, the __str__
will be used when you say "print c". But if you only have a
__repr__ that will be used.
More information about the Python-list
mailing list