Python OOP newbie question: C-Struct-esque constructions

Gerhard Häring gerhard.haering at gmx.de
Mon Aug 12 04:03:31 EDT 2002


In article <pan.2002.08.12.03.42.26.693124.11376 at example.com>, Jonathan S wrote:
> hello all,
> 
> I'm working on a news-downloading program for myself, and I want to take the
> list returned from the xover() method of the nntplib module and put it into a
> class so that each item in that list can be referenced by name. 
> 
> the way I figured to do it was something like this:
> 
> -------------------------------
> class xover_data():
>     frog = ""
>     s_frog = ""
>     spam = ""
>     spam_spam = ""
>     
>     def __init__(self, list):
> 		frog = list[0]
> 		s_frog = list[1]
> 		spam = list[2]
> 		spam_spam = list[3]
> 
> alist = ['ribbit', 's_ribbit', 'spam', 'spamspam']
> x = xover_data(alist)
> -------------------------------
> 
> that way I could access the items from x by name, like x.frog, x.s_frog, etc.
> 
> I can do what I need to do, but this solution seems a bit, well,
> unsophisticated. 

More importantly, it's wrong. To set instance attributes, you need to use self:
self.frog = list[0], etc.

> Any suggestions as to how to do this more python-esque? 

I see nothing wrong with your solution. You could implement it with less code,
but that's not necessarily more readable:

def __init__(self, list):
    self.frog, self.s_frog, self.spam, self.spam_spam = lists[:3]

Gerhard
-- 
Gerhard Häring
OPUS GmbH München
Tel.: +49 89 - 889 49 7 - 32
http://www.opus-gmbh.net/



More information about the Python-list mailing list