简体   繁体   中英

Calling Functions in Main Function

I've written a program and want to call the functions in the main. However, I've been receiving a SyntaxError. I'm not sure what I'm doing wrong. Here is my code, I've tried a few things but the main function won't call the rest of the functions.

class Matrix(object):
    def open_file():
        '''Opens the file if it exists, otherwise prints out error message'''
        Done = False
        while not Done: 
            try:
                File = input("Enter a filename: ").lower() #Asks user for a file to input
                Open_File = open(File, "r") #Open the file if it exists and reads it 
                Info = Open_File.readlines()[1:]
                Open_File.close() #Close the file 
                Done = True #Exits the while loop 
            except FileNotFoundError:
                print("Sorry that file doesn't exist!") #prints out error message if file doesn't exist
            return Info #Info is the file_pointer(fp)

    def __init__(self):  # This completed method is given
        '''Create and initialize your class attributes.'''
        self._matrix = {} #Intialize the matrix
        self._rooms = 0 #Set the rooms equal to zero

    def read_file(self, Info): #Info is equvalient to the file pointer or fp
        '''Build an adjacency matrix that you read from a file fp.'''
        self._rooms = Info.readline()
        self._rooms = int(self._rooms)
        for line in Info:
            a, b = map(int, line.split())
            self._matrix.setdefault(a, set()).add(b)
            self._matrix.setdefault(b, set()).add(a)

        return self._rooms and self._matrix

    def __str__(self):
        '''Return the adjacency matrix as a string.'''
        s = str(self._matrix)
        return s  #__str__ always returns a string

    def main(self):
        matrix = Matrix()
        info = matrix.open_file()
        matrix.read_file(info)
        s = str(matrix)
        print(s)

if __name__ == '__main__':
   m = Matrix()
   m.main()

A few things:

  • it's self.read_file , not just read_file . It's an instance method so you need to use self .
  • Same for __init__(self) , you need to call self.__init__ . Although typically you don't do this manually. You would "instantiate" the class via Matrix() .
  • You can't assign to a function call, so open_file() = Info simply doesn't make sense. Perhaps you mean info = open_file() .

It looks like you're a little confused about how to lay out your class. Try leaving main outside of the class, like this (untested):

def main:
    matrix = Matrix()
    info = matrix.open_file()
    matrix.read_file(info)
    s = str(matrix)
    print(s)

You will also need to dedent if __name__ == '__main__' to the global scope.

There is an error in your program's entry. ' if name == ' main ':'shouldn't be included in a Class. It should be global. And another, you want to call a member function of Matrix, but where is the object of Matrix. The code below is correct:

Class Matrix(object):
#################
        your codes
#################
 if __name__ == '__main__':
        m = Matrix()
        m.main()              

Ideally you may want to write something like below. Also, your open_file() has to be rewritten.

class Matrix(object):
    def open_file(self):
        File = input("Enter a filename: ").lower() #Asks user for a file to input 
        fp = open(File, "r") 
        return fp

#### Your matrix class code goes here

def main():
    myMatrix = Matrix()
    fp = myMatrix.open_file()
    ret = myMatrix.read_file(fp)
    print(myMatrix)


if __name__ == "__main__": 
    main()

the way this is posted

if __name__ == "__main__": 
    main()

is going to be executed when the class is defined -- not when the program is run. As written, the class won't have been instantiated so there's no Matrix object on which you can call main() .

You'll need to move the call out one indent, so it is aligned with the class definition, and then create an object before calling its main() :

  if __name__ == "__main__": 
    instance = Matrix()
    instance.main()

You've also got the assignments backwards in main() . It should read more like this:

 info = open_file()
 self.read_file(Info)
 s = __str__(self)
 print(s)

the open_file() method also has some issues. You want to create Info outside the scope of your loop so you know you've got it to return. Your comment indicates the Info is supposed to be the file pointer -- but it's not, as you wrote it. Open_File is the file pointer, and Info is the content of the file (at least, everything but the first line). Unless you're expecting a huge amount of data, it's probably easier to pass the contents -- or to combine open_file and read_file into the same function.

You also want to use the usual python pattern for opening and closing the files the with context manager - that will close your file for you.

Heres a quick and dirty version of Open_file and Read_file in one package.

def read_file(self):

   #get the filename first
   filename = None
   while not filename: 
       user_fn = input("Enter a filename: ").lower()
       if os.path.exists(user_fn):
           filename = user_fn
       else:
           print ("Sorry that file doesn't exist!") 

   # 'with' will automatically close the file for you
   with open(filename, 'rt') as filepointer:
       # file objects are iterable:
       for line in filepointer:
           a, b = map(int, line.split())
           self._matrix.setdefault(a, set()).add(b)
           self._matrix.setdefault(b, set()).add(a)

I'm not clear what self._matrix.setdefault(a, set()).add(b) is supposed to be doing for you here, but in syntactic terms you can simply the structure to "get the filename, open with with , iterate over it"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM