Problem with join in__str__() in class (newbie)

Stephen Hansen apt.shansen at gmail.com
Sun Aug 9 13:37:08 EDT 2009


   output += '\nKnown topics: %s' % (', '.join(str(self.topics)))


Your problem is here.

self.topics is a list of topic instances: but you're calling str() on the
list itself to turn the LIST itself into a string. Compare:

>>> x = [1,2,3]
>>> x
[1, 2, 3]
>>> str(x)
'[1, 2, 3]'

Now, after str(self.topics) is done, you have one big string. A string is a
sequence of characters (mostly). Calling ",".join(string) will do just what
you see there-- return a string with a comma between each character.

What you want to do, I assume, is call str() on each item in self.topics,
and join them.

That would be:

output += '\nKnown topics: %s' % ( ','.join(str(item) for item in
self.topics) )

That's a generator expression which will do what you want, I believe.
Provided your topic instances have a __str__ method that returns a string of
the form "t<topic_id>:<topic_name>".

Also, notice the code I've commented out. If I can get the join above to
> work (with your help) my next question is how to present the known experts
> in a comma separated list with only expert_id and name? I can't use the
> normal __str__() method (the one I'm writing here) because it prints too
> much information. Does that mean a join is out of the question?


Honestly, I think you are putting too much into the Expert class's __str__
method. I would make it do basically:

return "%s:%s" % (self.expert_id, self.name)

And then put the __str__ you're working on above in a different method which
does -- more. Call it 'dump' or something. That way you CAN just use the
normal str/__str__ from within this 'dump' and get what you want. str()
should return that object in its stringified form. Another method is a
better way to dump 'that object' and things 'around' it and that it 'knows'.

But if you really must have just str(expert) and have it return the big
chunk of information, your commented code looks about right. You'll have to
use your knowledge of how the internal expert class works instead of relying
on the experts just returning a str() of themselves. That's slightly bad.
But not horrible.

HTH,

--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090809/748f80b8/attachment-0001.html>


More information about the Python-list mailing list