我必须找到一种方法来获取已经给出的代码并通过使其成为面向对象的类来改进它。
此代码:已经给出,我们将其用于我们的新代码。文件 'students2txt' 被逐行提取(基于 ':' 进行拆分),并将StudentFileReader
类导入新的class StudentReport(object)
. 所以完成的项目应该给出一个学生名单,上面有身份证号码、名字和姓氏、gpa(所有信息都在'students2.txt'中给出,我只需要让代码打印所有信息。
filereader.py
:
class StudentFileReader:
def __init__(self, inputSrc):
self._inputSrc = inputSrc
self._inputFile = None
def open(self):
self._inputFile = open(self._inputSrc, 'r')
def close(self):
self._inputFile.close()
self._inputFile = None
def fetchRecord(self):
line = self._inputFile.readline()
if line == "":
return None
record = StudentRecord()
#change
record.idNum = int(line)
record.firstName = self._inputFile.readline().rstrip().rsplit(':')
record.lastName = self._inputFile.readline().rstrip().rsplit(':')
record.classCode = int(self._inputFile.readline())
record.gpa = float(self._inputFile.readline())
return record
class StudentRecord:
def __init__(self):
self.idNum = 0
self.firstName = ""
self.lastName = ""
self.classCode = 0
self.gpa = 0.0
新文件:
from filereader import StudentFileReader
class StudentReport(object):
def __init__(self):
self._theList = None
def loadRecords(self, filename):
self.reader = StudentFileReader(filename)
self.reader.open()
theList = []
record = self.reader.fetchRecord()
while record is not None:
theList.append(record)
record = self.reader.fetchRecord()
reader.close()
return theList
def sortByid(self):
self._studentList.sort(key = lambda rec: rec.idNum)
def sortByName(self):
pass
def __str__(self):
classNames = [ "", "Freshman", "Sophomore", "Junior", "Senior" ]
print( "LIST OF STUDENTS".center(50) )
print( "" )
print( "%-5s %-25s %-10s %-4s" % ('ID', 'NAME', 'CLASS', 'GPA'))
print( "%5s %25s %10s %4s" % ('-' * 5, '-' * 25, '-' * 10, '-' * 4))
# Print the body.
for record in theList :
print( "%5d %-25s %-10s %4.2f" % \
(record.idNum, \
record.lastName + ', ' + record.firstName,
classNames[record.classCode], record.gpa) )
# Add a footer.
print( "-" * 50 )
print( "Number of students:", len(theList) )
if __name__ == "__main__":
s = StudentReport()
s.loadRecords('students2.txt')
s.sortByName()
print str(s)
此代码取自教科书 Data Structures and Algorithms Using Python。我应该做一个面向对象的类。我已经开始StudentRecord
上课并写了,__init__
但我不确定在那之后该怎么做。当我尝试运行任何东西时,它会给我一个invalid literal for int() with base 10
错误。我对python很陌生,所以我不确定如何轻松地使任何面向对象的类..
编辑:是的,错误来自 fetchRecord 函数
Traceback (most recent call last):
File "C:\Users\...\studentreport.py", line 24, in <module>
s.loadRecords('students2.txt')
File "C:\Users\...\studentreport.py", line 13, in loadRecords
record = self.reader.fetchRecord()
File "C:\Users\...\filereader.py", line 22, in fetchRecord
record.idNum = int(line)
ValueError: invalid literal for int() with base 10: '10015:John:Smith:2:3.01\n'