4.8 作业

#
# 1、练习上课作业讲解的面向对象代码,明天默写
# 2、基于上课作业讲解的面向对象代码,扩写Student类
# 3、加入序列化与反序列化操作
# 4、对象之间的关联采用id号
# 5、可以通过id找到对应的文件,然后从文件中反序列化出执行的学校、班级、课程、学生对象






import pickle
import uuid


class School:
school_name='oldboy'
def __init__(self,nickname,addr):
self.uid=str(uuid.uuid4())
self.nickname=nickname
self.addr=addr
self.classes=[]
def related_class(self,class_uid):
self.classes.append(class_uid)

def tell_class(self):
print(self.nickname)
for class_uid in self.classes:
with open(f'{class_uid}.pkl','rb') as f:
res=pickle.load(f)
res.tell_course()
def save(self):
with open(f'{self.uid}.pkl','wb') as f:
pickle.dump(self,f)





class Class():
def __init__(self,name):
self.uid=str(uuid.uuid4())
self.name=name
self.course = None
def related_course(self,course_uid):
self.course=course_uid
def tell_course(self):
print('%s ' % self.name,end=' ')
with open(f'{self.course}.pkl', 'rb',) as f:
res=pickle.load(f)
res.tell_info()
def save(self):
with open(f'{self.uid}.pkl','wb',) as f:
pickle.dump(self,f)






class Course():
def __init__(self,name,period,price):
self.uid=str(uuid.uuid4())
self.name=name
self.period=period
self.price=price
def tell_info(self):
print('<课程名:%s 周期:%s 价钱:%s>' %(self.name,self.period,self.price))
def save(self):
with open(f'{self.uid}.pkl', 'wb')as f:
pickle.dump(self, f)

class Student():
def __init__(self,name,age,sex,id,):
self.uid=str(uuid.uuid4())
self.name=name
self.age=age
self.sex=sex
self.id=id
def related_class(self,class_uid):
self.classes=class_uid
def tell_info(self):
print(f'姓名:{self.name} 年龄:{self.age} 性别:{self.sex} 学号:{self.id}',end=" ")
with open(f'{self.classes}.pkl', 'rb')as f:
res=pickle.load(f)
res.tell_course()
def save(self):
with open(f'{self.uid}.pkl', 'wb')as f:
pickle.dump(self, f)


school_obj1=School('老男孩魔都校区','上海')
class_obj1 = Class('脱产14期')
course_obj1=Course('python全栈开发','6mons',20000)
class_obj1.related_course(course_obj1.uid)
student_obj1=Student('cyp',18,'male',1111)
student_obj1.related_class(class_obj1.uid)
school_obj1.related_class(class_obj1.uid)

school_obj1.save()
class_obj1.save()
student_obj1.save()
course_obj1.save()


# print(student_obj1.uid)
school_obj1.tell_class()
# class_obj1.tell_course()
# student_obj1.tell_info()
posted @ 2020-04-08 20:48  aksas  阅读(131)  评论(0编辑  收藏  举报