Problem with join in__str__() in class (newbie)

Piet van Oostrum piet at cs.uu.nl
Sun Aug 9 16:15:22 EDT 2009


>>>>> Fencer <no.i.dont at want.mail.from.spammers.com> (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
        self.name = name
        self.topics = topics
        self.known_experts = []
        
    def add_expert(self, expert):
        self.known_experts.append(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, self.name)
    
class Topic:
    '''A topic'''
    def __init__(self, id, name):
        self.topic_id = id
        self.name = name

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

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])

expert1.add_expert(expert2)

expert5 = Expert('e5', 'Carla', [topic5, topic6])
expert5.add_expert(expert1)
expert5.add_expert(expert2)

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 cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list