[英](Calling class) from Student import Student getting error that no module named Student
讓模塊 Student 工作時遇到問題。
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")
write_file() 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()
您不必導入模塊中已有的實體。 import
從不同的模塊或包中導入一些東西。 想象一下這種情況:
-root_directory
--module1 # contains class Student
--module2 # makes use of class Student
要使其工作,您必須在module2
from module1 import Student
中編寫或僅import module1
並像這樣使用它: module1.Student
。 但是,當您的代碼在一個模塊中時,您不必費心。 只需刪除該行。
如果您的Student()
class 在同一個模塊(文件)中,則無需導入。
如果您的Student()
class 位於另一個模塊中,則需要將其保存在與您的write_file()
function 模塊相同的目錄中。 需要將其命名為Student.py
如果是這種情況,請在命名模塊時考慮使用小寫名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.