使用class-python保存在文件中

我是python语言的新手。我想将一行保存到文件并加载文件的特定行。问题是我应该读取(加载)该文件的一行作为另一个(等级)类的对象,或者将一行作为另一个类(等级)的对象保存到文件中


我做到了,我想看看我做对了吗!


class Grade():


    def __init__(self,student_id=0,course_id=0,score=0):

        self._student_id = student_id

        self._course_id = course_id

        self._score = score



    @property

    def get(self):

        return str(self._student_id)+" "+str(self._course_id)+" "+str(float(self._score))

    @property


    def student_id(self):

        return str(self._student_id)

    @property

    def course_id(self):

        return str(self._course_id)

    @property

    def score(self):

        return str(self._score)


    @student_id.setter

    def student_id(self,student_id: int):

        self._sutdent_id = student_id

    @course_id.setter

    def course_id(self,course_id: int):

        self._course_id = course_id

    @score.setter

    def score(self,score: float):

        self._score = score



class CourseUtil():


    def __init__(self):

        self._address = ''


    def set_file(self,address):

        self._address = address


    def load(self,line_number):

        fp = open(self._address)

        for i, line in enumerate(fp):

            if i+1 == line_number:

                stri= line.split(" ")

                stdid = int(stri[0])

                corid = int(stri[1])

                score = float(stri[2])

                #here I want to save the #object that passed as argument to a file is it right?

               grade = Grade(stdid,corid,score)

                fp.close()

                return(grade)

        return print("None")

在保存功能中,我检查数据是否唯一,并且避免在文件末尾使用最后\ n


慕的地6264312
浏览 336回答 1
1回答

千巷猫影

您使用的保存类条目行的模型效率低下。相反,您可以以更好的方式存储数据。我假设每个学生ID是唯一且可哈希的(字符串或整数)。因此,您可以简单地拥有一本包含每个学生所有信息的字典:student_information = {    {student_id}: {        course_id: {course_id},        score: {score}    },    ... # more students}现在,如果您想获取学生的信息,您可以简单student_information[student_id]地获取所需的数据。例如,你可以这样做:grade = Grade(    student_id,     student_information[student_id]["course_id"],     student_information[student_id]["score"])您可以轻松地将此字典设置为类的实例变量CourseUtil。现在,@juanpa.arrivillaga 提到您应该使用它pickle来存储该信息(如果您想稍后返回)。使用Pickle,您可以将数据像字典一样存储到文件中并加载。也json可以帮助您做同样的事情。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python