[Tutor] Instantiating a list of strings into a list of classes

Benno Lang transmogribenno at gmail.com
Sat Mar 6 04:47:44 CET 2010

On 6 March 2010 10:38, Daryl V <vandyke.geospatial at gmail.com> wrote:
> I have a csv list of data, of the form:
> plot, utmN83_X, utmN83_Y, plot_radius_m
> Spring1,348545,3589235,13.2
> etc.
> I built a nifty ClassGPSPoint(Xpos,Ypos,plotRadius,workPaths) that eats the
> X&Y positions, the plot radius, and previously instantiated object holding
> all of the appropriate paths definitions to access the LiDAR LAS files.
> I make a nice CSV reader with one line (did I mention I LOVE python?)...
> plotReader =
> csv.reader(open("N:\\GIS_Projects\\095_ForestMetrics\\7_Analyses\\FinalCylinders\\Plots.csv"))
> What I want to do is use the first entry in that row (row[0]) as the
> variable name for the instantiated class.  I'd get an instantiated GPSPoint
> object called 'Spring1' that would yield all my methods and defined values
> (Spring1.pathLASfile, Spring1.perturbXY(), etc)....
> Hence, in pseudocode:
> for row in plotReader:
>    row[0] = GPSPoint(row[1],row[2],18.3,workPaths)

All you're doing here is replacing the name stored in row[0] with the
new GPSPoint object.

If I read your description correctly, I think what you're looking for
should behave like this:
# row read from CSV (I assume CSV values are always read as strings)
row = ['Spring1', '348545', '3589235', '13.2']
# what the code you want should do automatically
Spring1 = GPSPoint('348545','3589235','13.2', workPaths)

I don't know how to do that in Python - at a guess it would look
something like (pseudocode):
__module__.vars[row[0]] = GPSPoint(...)
Someone else probably knows how to do that, but I have a fairly strong
feeling that it's the wrong approach to your problem.
When you write your CSV file, each GPSPoint needs to know what its
variable name is, which doesn't seem to make a whole lot of sense. If
you have a set number of objects, then maybe you should just read and
write them in a known order - your program can call them anything it
likes; it won't affect the storage and loading of the data.
Alternatively, if for some reason you really want to associate a name
with each GPSPoint, I would suggest storing the points in a
dictionary, e.g.
points = {}
for row in plotReader:
    points[row[0]] = GPSPoint(row[1], row[2], row[3], workPaths)

Then when you need to write to a CSV, the name to go in the first
column is simply the key of that dictionary item.


More information about the Tutor mailing list