首页 > 解决方案 > 我得到一个```AttributeError:'int'对象没有属性'cityArray'```

问题描述

这是我的代码的一部分,我打印了一些值,而不是仅出于检查目的而返回它们,无论我在运行此代码时遇到属性错误。我确实定义了 cityArray 但它仍然会引发错误。

这基本上存储了一个 CSV 文件并运行线性搜索。



class City:#City classs
    def __init__(self,cid,cname,cstate,pop,cities):         #initilize the variables 

        self.cid= cid
        self.cname= cname                                  ##sets them all as empty lists
        self.cstate=cstate 
        self.pop= pop        
        self.cities= cities
        def __str__(self):                                  #return fuction to put out the final value
            print("cid: %s; cname: %s;cstate: %s; cases:%s"%(cid,cname,cstate,cities))

class COV19Library:#library classs

    def __init__(self):
        self.issorted=False 
        self.cityArray=[]
        self.size=0

    def LoadData(self, filename: str):           #loads the data feom excel sheet into those empty lists
        file = csv.DictReader(open(filename))    #as it is in a directory everything is linked
        for temp in file:

            cid = temp["City_ID"]      #all the city ID
            pop = temp['POP10']        #the population
            cities = temp['6/30/20']   #the latest number of case

            t = temp['City State'].split()    #splits city and state

            cstate = [word for word in t if word.isupper()]    #A comprehension and a Bool to identify states
            cname = [x for x in t if x not in cstate]          #remove the states from the initial list and we get cities 
            #print(cname)           #test
        for r in range(len(cid)):
            self.cityArray.append(City(cid,cname,cstate,pop,cities))

    def linearSearch(self, city, attribute):                    #linear search algorythum
        #print(cid)

        if attribute == "name":
            for r in cname:
                if r == city:
                    print(r)
                else:
                    print("City not found")
        elif attribute=="id":
            for z in self.cid:
                if z == city:
                    print(z)
                else:
                    print("City not found")```


ERROR: 
Traceback (most recent call last):
  File "Proj.py", line 142, in <module>
    COV19Library.LoadData(0,'cov19_city.csv') 
  File "Proj.py", line 36, in LoadData
    self.cityArray.append(City(cid,cname,cstate,pop,cities))
AttributeError: 'int' object has no attribute 'cityArray'

标签: pythonpython-3.xcsvattributeerror

解决方案


错误:

COV19Library.LoadData(0,'cov19_city.csv')

该调用将 0 作为第一个参数传递。分配给该编号的编号会self导致错误。

创建该类的一个实例并使用它:

covid = COV19Library()
covid.LoadData('a_file_name')

推荐阅读