[英]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_file
和read_file
组合到同一函数中可能会更容易。
您还希望使用普通的python模式with
context manager打开和关闭文件-这将为您关闭文件。
在一个软件包中,这是Open_file
和Read_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.