Problem with join in__str__() in class (newbie)

Piet van Oostrum piet at
Sun Aug 9 22:15:22 CEST 2009

>>>>> Fencer <no.i.dont at> (F) wrote:

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

>F> MRAB wrote:
>>> Try printing self.topics. It should always be a list of topics.

>F> Ah, yes, that made me find a bug when I was creating the Expert objects:
>F> the lists of known topics were not created properly. I should have posted
>F> more code I suppose! Thanks for the help, this problem has now been solved.
>F> I guess I can't use a join to print the known experts as I described in my
>F> first post.

Yes, you can. But you need an additional method that gives only the id
and name. Like this:

class Expert:
    '''An expert'''
    def __init__(self, id, name, topics):
        self.expert_id = id = name
        self.topics = topics
        self.known_experts = []
    def add_expert(self, expert):

    def __str__(self):
        output = (self.brief_str() +
                  '\nKnown topics: %s' % (', '.join(map(str, self.topics))) +
                  ('\nKnown experts: %s' %
                   (', '.join(exp.brief_str() for exp in self.known_experts))))
        return output

    def brief_str(self):
        '''Gives a brief description of the expert: just the id and name.'''
        return '%s:%s' % (self.expert_id,
class Topic:
    '''A topic'''
    def __init__(self, id, name):
        self.topic_id = id = name

    def __str__(self):
        return '%s:%s' % (self.topic_id,

topic1 = Topic('t1', 'Relativity')
topic2 = Topic('t2', 'Math')
topic5 = Topic('t5', 'Polemics')
topic6 = Topic('t6', 'The Parthenon')

expert1 = Expert('e1', 'Albert', [topic1])
expert2 = Expert('e2', 'Leonhard', [topic2])


expert5 = Expert('e5', 'Carla', [topic5, topic6])

for ex in expert1, expert2, expert5:
    print ex

(I prefer to use map instead of a list/iterator comprehension in this
particular case. With the known_experts that isn't possible, unless
brief_str is made into a static method)
Piet van Oostrum <piet at>
URL: [PGP 8DAE142BE17999C4]
Private email: piet at

More information about the Python-list mailing list