[Tutor] help with __str__

Alan Gauld alan.gauld at blueyonder.co.uk
Wed Sep 1 23:21:20 CEST 2004


> In the small program below, I assume that rep is
> concantenated when a new object is created
> (instantiated?).

rep only exists while __str__ is being executed
which is during a print operation. If it weren't 
then the print would only ever show the values 
the object had when created which is not what 
most users would expect!

> If so, it seems that if you put a print statement in
> the string method it should be printed out when
> an object is created but it's not. 

If you print self then Names.__str__() will be called
but if you print self.first then self.first.__str__() 
will be called which is not defined in the code you 
show us.

> confused. Is there somewhere that explains this in a
> simple way so even I can understand it?

Its almost as you think it is but you aren't doing what you 
think you are doing! :-)

You are printing out self.first. It is whatever oject you 
pass in and print will use whatever string representation 
it has. If you want to call your __str__ method you must 
print an instance of the Names class, ie self.

> class Names(object):
>         def __init__(self, first, last):
>             self.first = first
>             self.last = last
>             print self.first
> 
>         def __str__(self):
>             rep = self.first + " " + self.last
>             return rep

HTH,

Alan G.


More information about the Tutor mailing list