Using __repr__ or __str__ for own printable class?

Mads Orbesen Troest mads at troest.NEVERMORE.dk
Sat Apr 12 08:41:46 EDT 2003


Hi Pythoners;

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.

Which is the most correct to use; or should I even overload both? The 
documentation says __str__ is for the, quote, informal representation; 
whereas __repr__ is for the, quote, official representation. Furthermore, 
__reptr__ should, quote, look like an expresseion. I'm not quite sure what 
is meant by these distinctions. Is it that __repr__ is used by pickle and 
the like, and - thus - should represent the entire object state? Given that 
I simply want to determine what should happen when one tries to print an 
instance, do I assume correctly when I gather that __str__ would be the 
more appropriate of the two - or is there some other way I should achieve 
this?

Thanks in advance,
   /\/\\ads Orbesen Troest




More information about the Python-list mailing list