将csv文件中的值存储到类的属性中

时间:2019-06-18 04:52:46

标签: python csv

我正在尝试为调度问题编写代码。今天,我的代码有问题。我正在尝试将csv文件中的值存储到类的属性中。请帮助我理解它。

import math
import csv

from math import radians, sin, cos, acos

class masterTrainer:        #class generated for the master trainers for the whole state
    with open("mtData.csv", "r") as f_input:
        csv_input = csv.DictReader(f_input)
        for row in csv_input:
            masterTrainer.name = row['Name']
            masterTrainer.location = row['Location']
            masterTrainer.subject = row['Subject']
            masterTrainer.latitude = row['latitude']
            masterTrainer.longitude = row['longitude']

    def distanceCalculator(latitude1,longitude1,latitude2,longitude2):
        slat = radians(latitude1)
        slon = radians(longitude1)
        elat = radians(latitude2)
        elon = radians(longitude2)
        dist = 6371.01 * acos(sin(slat)*sin(elat) + cos(slat)*cos(elat)*cos(slon - elon))
        print("The distance is %.2fkm." % dist)

class venue:
    with open("venueData.csv", "r") as f_input:
        csv_input = csv.DictReader(f_input)
        for row in csv_input:
            venue.name = row['Name']
            venue.latitude = row['latitude']
            venue.longitude = row['longitude']

print(masterTrainer.distanceCalculator(float(masterTrainer.latitude),float(masterTrainer.longitude),float(venue.latitude),float(venue.longitude)),masterTrainer.name, venue.name)

上面的代码显示了属性错误。

AttributeError: type object 'masterTrainer' has no attribute 'latitude'

1 个答案:

答案 0 :(得分:0)

当您在python中声明一个类并希望将值存储在该类的某个成员上时,执行该操作的正确方法如下:

class NameOfClass:
    def __init__(self, something, ...): #of course change "..." to the rest of arguments
        self.someAttribute = something

因此,首先定义一个名为__init_\_(self, ...):的方法,并将您的with open(....) as ...:放入其中,然后将其中的所有masterTrainer.whatever更改为self.whatever