[Tutor] Creating class instances through iteration

spir ☣ denis.spir at gmail.com
Fri Apr 16 05:14:31 CEST 2010


On Thu, 15 Apr 2010 21:03:52 -0500
Tim Goddard <timgoddardsemail at gmail.com> wrote:

> I came across a situation where what I thought I wanted to do was to create
> a class that was spawned from data in a .csv file.  Where column 1 was the
> name I wanted to use for each instance.  I had it all figured out and
> working except for how to write a statement where the left hand side could
> be a changing identifier.
> 
> All I could figure out was how to create the same instance 50 times albeit
> in different ways.
> 
> For example each row would look like [name, value1, value2, value3], I
> planned on passing the three values as a tuple
> 
> The code would simply be:
> 
> for row in csvimport:
>     tuple = (row[1],row[2],row[3])
>     instancename = Classname(tuple)
> 
> How could I create different instances inside an iteration loop for each row
> ?

If I understand you properly, what you're trying to reinvent is a dict. For each row, use the name (which is data, too, right?) as key and the tuple oe whatever structure you like as value.
   thing[name] = tuple
An alternative, if you really want the names to be real var names, is to put all of that into an object as attributes, using the builtin func setattr:
   setattr(thing, name, tuple)

> Is it possible to change the name through modification of self attribute
> (wait is self an attribute?)

Don't understand why you want a class here.

> Are cats sleeping with dogs here or what?

???

Denis
________________________________

vit esse estrany ☣

spir.wikidot.com


More information about the Tutor mailing list