简体   繁体   English

在主函数中调用函数

[英]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. 但是,我一直在收到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. 这是我的代码,我已经尝试了一些方法,但是main函数不会调用其余函数。

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 . 它是self.read_file ,而不仅仅是read_file It's an instance method so you need to use self . 这是一个实例方法,因此您需要使用self
  • Same for __init__(self) , you need to call self.__init__ . __init__(self) ,您需要调用self.__init__ Although typically you don't do this manually. 虽然通常您不手动执行此操作。 You would "instantiate" the class via Matrix() . 您可以通过Matrix() “实例化”该类。
  • You can't assign to a function call, so open_file() = Info simply doesn't make sense. 您不能分配给函数调用,因此open_file() = Info根本没有意义。 Perhaps you mean info = open_file() . 也许您的意思是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): 尝试将main留在班级之外 ,例如(未经测试):

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. 您还需要if __name__ == '__main__' __ if __name__ == '__main__'是否为全局范围。

There is an error in your program's entry. 程序的输入错误。 ' if name == ' main ':'shouldn't be included in a Class. '如果name ==' main ':'不应包含在Class中。 It should be global. 它应该是全球性的。 And another, you want to call a member function of Matrix, but where is the object of Matrix. 另外,您想调用Matrix的成员函数,但是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. 另外,您的open_file()必须重写。

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() . 如所写,该类不会被实例化,因此没有可以调用main() Matrix对象。

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() : 您需要将调用移出一个缩进,使其与类定义对齐,然后在调用其main()之前创建一个对象:

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

You've also got the assignments backwards in main() . 您还可以在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. open_file()方法也有一些问题。 You want to create Info outside the scope of your loop so you know you've got it to return. 您想在循环范围之外创建Info ,以便您知道可以返回它。 Your comment indicates the Info is supposed to be the file pointer -- but it's not, as you wrote it. 您的注释指示该Info应该是文件指针-但并非如您所写。 Open_File is the file pointer, and Info is the content of the file (at least, everything but the first line). Open_File是文件指针, Info是文件的内容(至少,除了第一行以外的所有内容)。 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. 除非您期望大量的数据,否则传递内容或将open_fileread_file组合到同一函数中可能会更容易。

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. 您还希望使用普通的python模式with context manager打开和关闭文件-这将为您关闭文件。

Heres a quick and dirty version of Open_file and Read_file in one package. 在一个软件包中,这是Open_fileRead_file的快速而肮脏的版本。

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" 我不清楚self._matrix.setdefault(a, set()).add(b)应该在这里为您做什么,但是在语法上,您可以简单地使用以下结构:“获取文件名, with ,遍历它”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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