from dataclasses import dataclass
import os

@dataclass
class Stu:
    __slots__ = ['stu_id','name','age','sex']
    stu_id:int
    name:str
    age:int
    sex:str

    def __str__(self):
        return f'{self.stu_id},{self.name},{self.age},{self.sex}'

class StuSymMode:
    __slots__ = ['student_dic',]
    def __init__(self):
        self.student_dic={}
        #加载文件
        self.load_file()


    def add(self,id:int,name:str,age:int,sex:str):
        if id not in self.student_dic.keys():
            stu=Stu(stu_id=id,name=name,age=age,sex=sex)
            self.student_dic[id]=stu  #将学生对象添加到字典中
        else:
            return False, '学生信息已经存在!'

    def findall(self):
        return self.student_dic

    def findone(self,id:int):
        if id not in self.student_dic.keys():
            return False,'该学生不存在'
        obj=self.student_dic.get(id)
        return True,obj

    def delete(self,id):
        if id not in self.student_dic.keys():
            return False, '该学生不存在'

        del self.student_dic[id]
        return True,self.student_dic

    def update(self,id,name,age,sex):
        if id not in self.student_dic.keys():
            return False, '该学生不存在'
        self.student_dic[id].name=name
        self.student_dic[id].age=age
        self.student_dic[id].sex = sex

    def save(self):
        f=open('student.txt','w',encoding='utf-8')
        # f.write(str(self.student_dic))
        for obj in self.student_dic.values():
            f.write(str(obj)+'\n')
        f.close()

        # s=''
        # for obj in self.student_dic.values(): #
        #     s+=str(obj)+'\n'
        # print(s)

    def load_file(self):

        if os.path.exists('student.txt'):
            f=open('student.txt','r',encoding='utf-8')
            stu_str_list=f.readlines()
            print(stu_str_list)
            stu_str_list=[i.strip() for i in stu_str_list] #去掉字符串行号符
            # print(stu_str_list)
            for stu_list in stu_str_list:
                data=stu_list.split(',')
                 #拆包
                 #stu_obj=Stu(*data)             
                stu_obj=Stu(int(data[0]),data[1],int(data[2]),data[3])
                self.student_dic[int(data[0])]=stu_obj

            f.close()








if __name__ == '__main__':
    mode=StuSymMode()
    # mode.add(1, 'xuan', 8, '女')
    # mode.add(2, 'shui', 13, '男')
    print(mode.findall())


    # mode.load_file()

06-09 21:58