Using __repr__ or __str__ for own printable class?
Roy Smith
roy at panix.com
Sat Apr 12 08:59:43 EDT 2003
Mads Orbesen Troest <mads at troest.NEVERMORE.dk> wrote:
> If I create a class which I want to be able to print like this ...
> tst = myclass()
> exp = r"test: %(intepol)s";
> print exp % { 'intepol':tst }
>
> ... it seems I have two choices, either of which appear to work. I can
> overload the __str__ or the __repr__ method.
Most likely, what you want to do is define a __str__ method for your
class.
The basic concept is that __str__ produces a string the is easy for
humans to read, and __repr__ produces a string which the python parser
can read and regenerate the original object. For complex data
structures, __repr__ is usually of limited value.
More information about the Python-list
mailing list