TransWikia.com

Python: Error in assigning a method result to a instance variable on a constructor

Stack Overflow Asked by Jorge Díaz on December 22, 2021

When I run this code I get a message saying that name ‘readFile’ is not defined. How can I write this so that I don’t have this error? I want to assign a list of lists to self.cities. Thank you.

class TSP:

    def __init__(self, filename):
        self.filename = filename
        self.cities = readFile()

    def readFile(self):   
        f = open(self.filename, 'r')
        citieslist = []
        res = f.readlines()
        for line in res:
            aList = list(line.split(';'))
            for i in range(0,len(aList)):
                aList[i] = aList[i].rstrip('n')
            citieslist.append(aList)
        return readFile (self.cities)
        f.close()
        

2 Answers

SInce you have basically negated any future use of readFile by omitting an argument for filename in it's interface, you could just do the below.

We simply use a with statement to process the file, and a list comprehension to concoct the results.

class TSP:
    def __init__(self, filename):
        with open(filename, 'r') as f:
            self.cities = [line.strip().split(';') for line in f.readlines()]

        #do something with self.cities here
    
                
tsp = TSP('somefile.ext')

Answered by Michael Guidry on December 22, 2021

You have not used self in init. You have a recursive function at readFile. You closed the file after returning from function readFile. You only have to strip the whole line to cut the n off. Also returning is unnecessary since you can work with references inside Class.

class TSP:
    def __init__(self, filename):
        self.filename = filename
        self.cities = self.readFile()

    def readFile(self):   
        f = open(self.filename, 'r')
        citieslist = []
        res = f.readlines()
        for city in res:
            city = city.strip().split(';')
            citieslist.append(city)
        f.close()
        return citieslist

Answered by nagyl on December 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP