how to use __str__ and __repr__?
jimka at rdrop.com
Tue Jun 8 08:12:22 CEST 2004
hmm, even when i change it to calling str() rather than __str__()
it does not work.
print another() # works
another().str() # does not work
does anyone know why?
Peter Hansen wrote:
> Jim Newton wrote:
>> i read that in the documenation. and i assumed from that that
>> print another()
>> actually prints the string returned from another().__str__()
>> and thus __str__ must be being inherited from the superclass
>> of another, but apparently print does something different.
>> why does print another() actually print something rather than
>> complaining that there is no __str__ defined?
> I believe print basically calls str(obj) on the object, and
> str() is a builtin which (I believe) basically tries to call
> __str__() and if that is not defined, calls __repr__(). If
> __repr__ is not defined, it probably defers to a standard
> representation based on the id() of the object, which is
> always defined.
> Not sure what else you're trying to do (I haven't read your
> full post) but I believe this and some thought should answer
> for pretty much everything you're seeing.
> Note that you should probably never call __str__() directly,
> but call the str() builtin instead. Same for __repr__()
> versus the repr() builtin.
More information about the Python-list