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

2024-09-27 07:32:54 发布

您现在位置: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 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_file():
试试看:
“打开文件以进行读取”
f=open('StudentData.txt','r')
“”“在列表中逐行读取文件:readlines()”“”
contents=f.readlines() 打印(内容)
“计算并打印行数”
numOfLInes=len(内容)
打印(“文件中的行数:{}”。格式(numOfLInes))
“关闭文件”
f、 close()
IOError除外:
打印(“无法打开文件”) 读取文件()


Tags: 文件ofnameselffordefcontentsfile
2条回答

如果Student()类位于同一模块(文件)中,则无需导入它

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

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

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

-root_directory
 module1 # contains class Student
 module2 # makes use of class Student 

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

相关问题 更多 >

    热门问题