0

I am attempting to extract data from a csv and place the resulting data into a class that I have written.

Although I believe i have created multiple instantiations of the class, the lists which are members of the class seem to be shared across instances.

Here is the class:

class Sample:
def __init__(self, name, wavelengths=[], means=[]):
    self.name = name
    self.wavelengths = wavelengths
    self.means = means
def prettyprint(self):
    print(self.name)
    for i in range(0, len(self.means)):
        print(i, self.wavelengths[i], self.means[i])

Here is the code:

import csv
from mystructs import Sample

file_in = 'test2.csv'

accepted_names = {'a', 'b'}
samples = {}

with open(file_in, 'rb') as csvfile:
    reader = csv.reader(csvfile, delimiter=';')
    for row in reader:
        if len(row) > 0 and row[0] in accepted_names:
            n = row[0] #extracts name
            w = int(row[8]) #wavelength
            m = float(row[5]) #mean
            if row[0] not in samples:
                samples[n] = Sample(n)
            samples[n].wavelengths.append(w)
            samples[n].means.append(m)
            print(n,samples[n].means[-1])

for key in samples:
    samples[key].prettyprint()

The simplified sample file I've been using

here;we;go;
a;;;;;1.1;;;1;
a;;;;;1.2;;;10;
a;;;;;1.3;;;100;
b;;;;;2.1;;;2;
b;;;;;2.2;;;20;
b;;;;;2.3;;;200;

And the output:

('a', 1.1)
('a', 1.2)
('a', 1.3)
('b', 2.1)
('b', 2.2)
('b', 2.3)
a
(0, 1, 1.1)
(1, 10, 1.2)
(2, 100, 1.3)
(3, 2, 2.1)
(4, 20, 2.2)
(5, 200, 2.3)
b
(0, 1, 1.1)
(1, 10, 1.2)
(2, 100, 1.3)
(3, 2, 2.1)
(4, 20, 2.2)
(5, 200, 2.3)

I have a feeling the mistake is simply some misunderstanding of object oriented programming. Any help would be much appreciated.

0 Answers0