Python (调用类)从Student导入Student获取错误,没有名为Student的模块

Python (调用类)从Student导入Student获取错误,没有名为Student的模块,python,Python,在让模块学生工作时遇到问题。 def read_file(): try: """Open file for reading""" f = open('StudentData.txt', 'r') """Read file line by line in a list: readlines()""" contents = f.readlines() print(contents) """Calculate and print number o

在让模块学生工作时遇到问题。 def read_file():
try:
"""Open file for reading"""
f = open('StudentData.txt', 'r')
"""Read file line by line in a list: readlines()"""
contents = f.readlines() print(contents)
"""Calculate and print number of lines"""
numOfLInes = len(contents)
print("Number of lines in the file: {}".format(numOfLInes))
"""Close File"""
f.close()
except IOError:
print("File could not be opened") read_file()

class Student(object): def init(self): self.name = 'NoName' self.exam1 = 0.0 self.exam2 = 0.0 self.finalexam = 0.0 self.totalScore = 0.0 def setData(self, name, exam1, exam2, finalexam, totalScore = 0.0): self.name = name self.exam1 = exam1 self.exam2 = exam2 self.finalexam = finalexam self.totalScore = totalScore def calcFinalScore(self): self.totalScore = (self.exam1 + self.exam2 + self.finalexam) / 3 return self.totalScore

from Student import Student # This line appears to me to be the problem def write_file(): try: file= open("new.txt", "a")

           print("Enter student name")
           name = input()
           print("Enter score for exam 1 (out of 100)")
           e1 = float(input())
           print("Enter score for exam 2 (out of 100)")
           e2 = float(input())
           print("Enter score for final exam (out of 100)")
           final = float(input())
           student1 = Student()
           student1.setData(name,e1,e2,final)

           score = student1.calcFinalScore()

           file.write(name + " " + str(score))

           file.close()
    except:
           print("File could not be opened")
写入文件 def read_文件: 尝试: 打开文件进行读取 f=打开'StudentData.txt','r' 在列表中逐行读取文件:readlines contents=f.readlines 印刷内容 计算并打印行数 numOfLInes=lencontents 打印文件中的行数:{}.formatnumOfLInes 关闭文件 f、 接近 除IOError外: 无法打开打印文件 读取文件


您不必导入模块中已有的实体。导入从不同的模块或包导入某些内容。想象一下这种情况:

要使其工作,您必须从module1 import Student中写入module2,或者只需导入module1并像这样使用它:module1.Student。但是,当您的代码在一个模块中时,您不必费心。把那条线去掉

如果您的学生类位于同一模块文件中,则无需导入它

如果您的学生类位于另一个模块中,则需要使用write_file函数将其保存在与该模块相同的目录中。它需要命名为Student.py


如果是这种情况,请考虑在命名模块时使用小写名称。

请尝试以可读的方式格式化您的答案。对您的问题和问题有一个清晰的总结,然后是所需的代码。注意:您应该使用上下文管理器来处理文件对象。变量和函数名应遵循小写字母_加下划线的样式,除非有充分的理由不这样做。定义初始自我->定义初始自我。
-root_directory
--module1 # contains class Student
--module2 # makes use of class Student