首页 > 代码库 > Python基础day-19[面向对象:18天附]
Python基础day-19[面向对象:18天附]
类组合的是示例:
class People: def __init__(self,name,age,sex): self.name = name self.age = age self.sex = sex class Teacher(People): def __init__(self,name,age,sex,job,company): People.__init__(self,name,age,sex) self.job = job self.company = company self.course = [] #定义老师类的课程属性初始为一个 空的列表 def dis_info(self): print(‘‘‘==================%s info=================== Name:%s Age:%s Sex:%s Job:%s Company:%s ‘‘‘%(self.name,self.name,self.age,self.sex,self.job,self.company)) def dis_course_info(self): #定义打印老师类的课程信息 if ‘course‘ in self.__dict__: #判断 对象属性中是否有 course属性 for i in self.course: #如果有就打印出来 i.dis_course() class Student(People): def __init__(self,name,age,sex,classroom,school): People.__init__(self,name,age,sex) self.classroom = classroom self.school = school self.course = [] def dis_info(self): print(‘‘‘==================%s info=================== Name:%s Age:%s Sex:%s Classroom:%s School:%s ‘‘‘%(self.name,self.name,self.age,self.sex,self.classroom,self.school)) def dis_course_info(self): if ‘course‘ in self.__dict__: for i in self.course: i.dis_course() class Course: #定义的课程类 def __init__(self,course,price,period): self.course = course self.price = price self.period = period def dis_course(self): #打印课程信息 print(‘‘‘ Course Name:%s Course Price:%s Course Period:%s ‘‘‘%(self.course,self.price,self.period)) egon = Teacher(‘egon‘,18,‘male‘,‘teach‘,‘Oldboy‘) ldsly = Student(‘ldsly‘,23,‘male‘,‘PythonS5‘,‘Oldboy‘) python = Course(‘python‘,15800,‘6month‘) #使用 课程类实例化 课程 linux = Course(‘linux‘,12000,‘5month‘) egon.course.append(python) #给老师类实例化的对象 添加 课程 egon.course.append(linux) ldsly.course.append(python) egon.dis_course_info() ldsly.dis_course_info() egon.dis_info() ldsly.dis_info() 执行结果: D:\Python\Python36-32\python.exe E:/Python/DAY-19/默写内容.py Course Name:python Course Price:15800 Course Period:6month Course Name:linux Course Price:12000 Course Period:5month Course Name:python Course Price:15800 Course Period:6month ==================egon info=================== Name:egon Age:18 Sex:male Job:teach Company:Oldboy ==================ldsly info=================== Name:ldsly Age:23 Sex:male Classroom:PythonS5 School:Oldboy Process finished with exit code 0
生成的对象的序列化反序列化:
import pickle # class Student: def __init__(self,name,age,sex): #对象反序列化之后 需要在内存中寻找自己所属的类,如果没有会报错 self.name = name self.age = age self.sex = sex ldsly = Student(‘ldsly‘,23,‘male‘) with open(‘student.pkl‘,‘wb‘) as f: #序列化对象 ldsly res = pickle.dumps(ldsly) f.write(res) with open(‘student.pkl‘,‘rb‘) as f: #反序列化 res = f.read() ldsly = pickle.loads(res) #还原 对象ldsly print(ldsly.name,ldsly.age,ldsly.sex) 执行结果: D:\Python\Python36-32\python.exe E:/Python/DAY-19/序列化.py ldsly 23 male Process finished with exit code 0
Python基础day-19[面向对象:18天附]
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。