Using __repr__ or __str__ for own printable class?

Greg Ewing (using ckea25d02 at
Tue Apr 15 04:53:00 CEST 2003

Mads Orbesen Troest wrote:
> But then one wouldn't be able to do a standard "print" of the class, would 
> one?

No, you'd have to say

   print myStringRep(someInstanceOfMyClass)

But this is only an issue if you're printing a built-in
container such as a list. You could just as well make
the __str__ of MyClass do whatever myStringRep does.
However, if any of the instance variables of MyClass
are built-in containers, you would have to not simply
str() them, but treat them more carefully.

 > I would like to be able to  do this ...
> 	print someInstanceOfMyClass
> This works with __str__ but 
> I was/am afraid if this overriding of __str__ will conflict with other uses 
> of __str__ and/or __repr__.

If it works for you, then that's fine. The only other
built-in use of __str__ that I can think of is the
str() function. If you're happy for anyone who calls
str() on your class to get the same result, then
you don't need to worry.

Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand

More information about the Python-list mailing list