Как я мог бы переписать эту функцию, чтобы включить мой цикл «для полосы в файле:» в каждую функцию моего кода, а не в мой метод конструктора

#python #function #methods

#питон #функция #методы

Вопрос:

Это мой код. Я хотел бы переместить цикл «для полосы в файле:» в моем методе в каждую функцию, так как мое назначение не допускает никаких циклов в методе инструктора, о которых я сначала не знал. Я пытался сделать это пару раз, но каждый раз мне не удавалось заставить код функционировать одинаково. Я новичок.

 from country import Country  class CountryCatalogue:  def __init__(self, countryFile): # constructor method that takes name of file  self.countryCat = [] # The instance variable country cat needed  file = open(countryFile, "r") # open and read the file  for strip in file:  strip = strip.strip()  data = strip.split('|') # Remove '|' in each line  clean_data = Country(data[0], data[2], data[3], data[1]) # Create an object to country  self.countryCat.append(clean_data) # Append the item to the list  file.close() # Close the file  def setPopulationOfCountry(self, country, population):  for pop in range(len(self.countryCat)): # iterate through countryCat  if self.countryCat[pop].getName() == country.getName():  self.countryCat[pop].setPopulation(population) #updating data if needed  def setAreaOfCountry(self, country, area):  for air in range(len(self.countryCat)): # iterate through countryCat  if self.countryCat[air].getName() == country.getName():  self.countryCat[air].setArea(area) #update data if needed  def setContinentOfCountry(self, country, continent):  for cont in range(len(self.countryCat)): # iterate through countryCat  if self.countryCat[cont].getName() == country.getName():  self.countryCat[cont].setContinent(continent) #update data if needed  def findCountry(self,country):  for clean_data in self.countryCat: # iterate through countryCat  if clean_data.getName() == country.getName(): # check to see if country is in countryCat  return country  return None # if not return's none  def addCountry(self,countryName,pop,area,cont): # method used to add new country to countrycat  exists = False  for x in range(len(self.countryCat)): # iterate through countryCat  if self.countryCat[x].getName() == countryName: # added succesfully  exists = True  if exists:  return False  else:  cntry_found = Country(countryName, pop, area, cont) # adding to country  self.countryCat.append(cntry_found)  return True  def printCountryCatalogue(self): # printer method  for x in self.countryCat:  print(repr(x)) # making use of repr method from country  def saveCountryCatalogue(self,fname):  total = 0  for x in range(len(self.countryCat)): # Sort the list  for j in range(x):  if self.countryCat[x].getName() lt; self.countryCat[j].getName():  t = self.countryCat[x]  self.countryCat[x] = self.countryCat[j]  self.countryCat[j] = t  file = open(fname, "w") # Open the file  file.write("Country|Continent|Population|Arean")  # Use for loop to iterate through all objects  for cntry in self.countryCat:  file.write(cntry.getName()   "|"   cntry.getContinent()   "|"   cntry.getPopulation()   "|"   cntry.getArea()   "n")  total=total 1  # Close the file  file.close()  if(total==len(self.countryCat)):  return total  else:  return -1  

Комментарии:

1. Поместите его в другие методы, которые вы можете вызвать, откуда вам нужно.

2. Как бы вы это написали