试图找到一些关于如何在类和子类中使用集合和字典的信息。我有一项任务,指示我们创建一个类Country
和一个子类CountryCatalogue
。然后,在函数中创建一个名为cDictionary
和catalogue
的字典(可以是列表,集合或字典,我决定使用set,但可能需要根据您的建议进行更改)。我遇到的问题是,当我初始化cDictionary
和catalogue
class CountryCatalogue(Country):
下它告诉我没有的功能,在它之下(例如,__init__()
,findCountry()
,addCountry()
,等等)可以“看见” catalogue
被初始化,并给我一个当我尝试访问这些列表中的catalogue
时出现“无效变量”错误,如果我在__init__
函数中初始化它们,则会发生同样的情况;其他功能不能看到它,但至少__init__
正常工作。类函数中的集合和字典
不幸的是,类的糟糕和我们被教了所有单独的重要“主题”的蟒蛇,但没有如何一起使用它们。
实施例:
class CountryCatalogue(Country):
def __init__(self, filename = "", name = "", pop = 0, area = 0, continent = ""):
cDictionary = {} #Initializing the cDictionary and catalogue here leads to errors in other functions
catalogue = []
super().__init__(name = "",pop = 0,area = 0,continent = "")
fillcdict = open("continent.txt") #not really important for the problem
linescdict = fillcdict.readlines()[1:]
for line in linescdict:
entries1 = line.split(",")
country = str(entries1[0])
continentwrong = str(entries1[1])
entries2 = continentwrong.split ("\n")
continent = str(entries2[0])
cDictionary["keywords"] = country
cDictionary["values"] = continent
self._continent = continent
fillcatdict = open(filename)
linescatalogue = fillcatdict.readlines()[1:]
for line in linescatalogue:
entries = line.split("|")
countrydata = str(entries[0])
populationdata = entries[1]
areadata = entries[2]
catalogue.append(countrydata)
def findCountry(self): #So, when I try and use catalogue in this function I get a 'unresolved reference' note in Pycharm and a "invalid variable' error if I run the problem
findcountinp = input("Please enter a country name: ")
if findcountinp in catalogue:
return self._name+"|"+self._continent+"|"+self._area+"|"+self._population
else:
return "Country not found!"
我该如何从目录中删除东西? 目录将是一个单独的数据文件中提供的所有国家的列表。在另一个功能中,我没有在问题中包含,我必须要求用户输入一个国家,然后搜索目录并删除他们输入的国家。 – MezyMinzy
'self.catalogue.pop(index)'或'self.catalogue.remove(country)'。你的设计是可疑的。你确实意识到将CountryCatalogue作为Country的子类是没有意义的,对吗?一组国家又是一个国家呢?或者,如果每个“国家”都创建为“国家目录”,则每个国家/地区的成员列表“目录”将会不同。您将拥有与国家一样多的目录。 –
那么,国家的其中一项功能是setPopulationDensity,您可以在其中计算人口密度。但是,在CountryCatalogue中,您有一个函数filterCountriesByPopDensity,它指示:“请求用户输入人口密度范围的下限和上限,然后查找所有人口密度在该范围内的国家。”无处不在计算人口密度,它表明人口密度已经计算出来(我从国家班级中假设),但我不知道如何从一个班级获得功能并在另一个班级中使用 – MezyMinzy