Python OOP newbie question: C-Struct-esque constructions

Jay O'Connor joconnor at cybermesa.com
Mon Aug 12 02:35:16 CEST 2002


In article <pan.2002.08.12.03.42.26.693124.11376 at example.com>, "Jonathan
S" <python_hacker at example.com> 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.
> 
> Any suggestions as to how to do this more python-esque?


I'm not sure if it's moer 'python-esque' but you can take advantage of
the fact that object instance variables are held in an internal
dictionary indexed by name and build a mapping from array elements to
instance variables.  Here's a sample

#!/usr/bin/python


class xover_data:

	# Class variable of instance variable names, order is important
	VariableNames = ["frog", "s_frog", "spam"]
	
	def __init__ (self, aList):
	
		# use the class variable information to populate my instance 
		#variables from the given list

		for i in range (0, len(xover_data.VariableNames)):
			self.__dict__[xover_data.VariableNames[i]] = aList[i]
			


# -- Main --

testList = ["ribbit", "s_ribbit", "spam"]

data = xover_data (testList)

print data.frog


-- 
Jay O'Connor
joconnor at cybermesa.com
http://www.r4h.org/r4hsoftware



More information about the Python-list mailing list