Python OOP newbie question: C-Struct-esque constructions

Thomas Jensen spam at ob_scure.dk
Mon Aug 12 04:02:37 EDT 2002


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 = ""

Are you aware that you are assigning class attributes here?

>     def __init__(self, list):
> 		frog = list[0]
> 		s_frog = list[1]
> 		spam = list[2]
> 		spam_spam = list[3]

You must use self.frog, etc if you wish to assign instance attributes.

> alist = ['ribbit', 's_ribbit', 'spam', 'spamspam']
> x = xover_data(alist)
> -------------------------------

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

Perhaps something like this:

   class XOverData:
     def __init__(self, names, values):
       pairs = zip(names, values)
       temporary_dict = dict(pairs)
       self.__dict__.update(temporary_dict)

Test it like this:

   def test():
     names = ['spam', 'eggs', 'bacon']
     values = [1, 'test', None]
     xover_data = XOverData(names, values)
     print xover_data.spam
     print xover_data.eggs
     print xover_data.bacon

   test()


The class constructor could also be written as:

   self.__dict__.update(dict(zip(names, values)))

-- 
Best Regards
Thomas Jensen
(remove underscore in email address to mail me)




More information about the Python-list mailing list