簡體   English   中英

在主函數中調用函數

[英]Calling Functions in Main Function

我已經編寫了一個程序,想在主體中調用這些函數。 但是,我一直在收到SyntaxError。 我不確定自己在做什么錯。 這是我的代碼,我已經嘗試了一些方法,但是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()

一些東西:

  • 它是self.read_file ,而不僅僅是read_file 這是一個實例方法,因此您需要使用self
  • __init__(self) ,您需要調用self.__init__ 雖然通常您不手動執行此操作。 您可以通過Matrix() “實例化”該類。
  • 您不能分配給函數調用,因此open_file() = Info根本沒有意義。 也許您的意思是info = open_file()

您似乎對如何布置課程有點困惑。 嘗試將main留在班級之外 ,例如(未經測試):

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

您還需要if __name__ == '__main__' __ if __name__ == '__main__'是否為全局范圍。

程序的輸入錯誤。 '如果name ==' main ':'不應包含在Class中。 它應該是全球性的。 另外,您想調用Matrix的成員函數,但是Matrix的對象在哪里。 下面的代碼是正確的:

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

理想情況下,您可能需要編寫如下內容。 另外,您的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()

發布方式

if __name__ == "__main__": 
    main()

將在定義類時執行-而不是在程序運行時執行。 如所寫,該類不會被實例化,因此沒有可以調用main() Matrix對象。

您需要將調用移出一個縮進,使其與類定義對齊,然后在調用其main()之前創建一個對象:

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

您還可以在main()向后分配賦值。 它應顯示如下:

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

open_file()方法也有一些問題。 您想在循環范圍之外創建Info ,以便您知道可以返回它。 您的注釋指示該Info應該是文件指針-但並非如您所寫。 Open_File是文件指針, Info是文件的內容(至少,除了第一行以外的所有內容)。 除非您期望大量的數據,否則傳遞內容或將open_fileread_file組合到同一函數中可能會更容易。

您還希望使用普通的python模式with context manager打開和關閉文件-這將為您關閉文件。

在一個軟件包中,這是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)

我不清楚self._matrix.setdefault(a, set()).add(b)應該在這里為您做什么,但是在語法上,您可以簡單地使用以下結構:“獲取文件名, with ,遍歷它”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM