# geter seter 方法 ''' 10个学生 id : 1001 name :student1 age : 20 grade :59 sex : man score : 59 ''' import codecs class StudentMessage(): __id = int() __name = str() __score = int() def getId(self): return self.__id def setId(self,id): self.__id = id def getName(self): return self.__name def setName(self,name): self.__name = name def getScore(self): return self.__score def setScore(self,score): self.__score = score # 对象的保存,保存类 # 类的传递 class Student(object): def __init__(self,id,name,score): self.id = id self.name = name self.score = score class InitStu(object): def __init__(self): self.student = list() def initStuden(self): # 用来获取数据,这里手动添加 self.student.append(Student(1001, "aa", 99)) self.student.append(Student(1002, "ab", 89)) self.student.append(Student(1003, "ac", 79)) self.student.append(Student(1004, "ad", 69)) self.student.append(Student(1005, "ae", 59)) self.student.append(Student(1006, "af", 49)) def sort(self): # 对成绩进行排序 return sorted(self.student, key=lambda stu: stu.score) def writeFile(self,sortStudents): # 将排序后的结果保存文件 with codecs.open("sortStudent.txt","w") as f: for i in sortStudents: f.write("id = {0}".format(i.id)) f.write("\t") f.write("name = {0}".format(i.name)) f.write("\t") f.write("score = {0}".format(i.score)) f.write("\n") def main(): student = InitStu() student.initStuden() sortStudents =student.sort() student.writeFile(sortStudents) if __name__ == '__main__': main()
转载于:https://my.oschina.net/u/3824134/blog/1799028