为了账号安全,请及时绑定邮箱和手机立即绑定

使用class-python保存在文件中

使用class-python保存在文件中

慕的地6264312 2021-05-31 06:58:21
我是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 = scoreclass 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
查看完整描述

1 回答

?
千巷猫影

TA贡献1829条经验 获得超7个赞

您使用的保存类条目行的模型效率低下。相反,您可以以更好的方式存储数据。我假设每个学生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可以帮助您做同样的事情。


查看完整回答
反对 回复 2021-06-01
  • 1 回答
  • 0 关注
  • 299 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号