如何正确地在此类中调用该函数?

时间:2019-10-23 19:20:04

标签: python-2.7 class self

我的问题是,如何通过在读取的CSV中输入两个可用的城市名称来正确调用我的City类中的printDistance函数。我打算使用与这两个城市关联的值来执行方程式。

但是当我输入两个城市(巴黎和东京)进行测试时,我收到"NameError: name 'Paris' is not defined.",我试图让selfothercity能够识别我输入的城市。

class City:
    def __init__ (self, name, label, lat, lon, pop_dict):
        self.name = name
        self.label = label
        self.lat = lat
        self.lon = lon
        self.pop_dict = pop_dict
        lat1 = float(lat_self)
        lat2 = float(lat_othercity)
        lon1 = float(lon_self)
        lon2 = float(lon_othercity)
        radian_lat1 = math.radians(lat1)
        radian_lat2 = math.radians(lat2)
        radian_lon1 = math.radians(lon1)
        radian_lon2 = math.radians(lon2)
        AD = (math.acos(math.sin(radian_lat1) * math.sin(radian_lat2) + math.cos(radian_lat1) * math.cos(radian_lat2) * math.cos(radian_lon1 - radian_lon2)))
        print "The distance between", self, "and", othercity, "is", int((AD * 6300)), "kilometers."

    @classmethod 
    def printDistance(self, othercity):     
        lat_self = self.lat
        lat_othercity = othercity.lat
        lon_self = self.lon
        lon_othercity = othercity.lon

Cities = []

f = open("CityPop.csv","r")
header = f.readline()
header = header.strip().split(",")
for line in f:
    record = line.strip().split(",")
    pop = {}
    for i in range (5, 14):
        pop[header[i]] = record[i]
    newCity = City(name = record[3], label = record[4], lat = record[1], lon = record[2], pop_dict = pop)
    Cities.append(newCity)


print City.printDistance(Paris, Tokyo) #example

0 个答案:

没有答案