在Python dict中引用类的实例

时间:2016-10-16 12:00:19

标签: python class csv dictionary member

我正在尝试从csv中提取数据并将结果数据放入我编写的类中。

虽然我相信我已经创建了该类的多个实例,但是作为该类成员的列表似乎是跨实例共享的。

这是班级:

``

以下是代码:

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])

我一直在使用的简化示例文件

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()

输出:

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;

我有一种感觉,错误只是对面向对象编程的一些误解。任何帮助将不胜感激。

0 个答案:

没有答案