# 一。组合 # 1、什么是组合: # 组合就是一个类的对象具备某一个属性,该属性的值是指向另外一个类的对象 # # 2、为何用组合 # 组合也是用来解决类与类之间代码冗余问题的 # # 3、如何用组合 # class OldboyPeople:#父类 # school='oldboy' # # def __init__(self,name,age,sex): # self.name=name # self.age=age # self.sex=sex # # class OldboyStudent(OldboyPeople):#继承父类 # def __init__(self,name,age,sex,stu_id): # OldboyPeople.__init__(self,name,age,sex)#指明道姓的方式传值,无需继承 # self.stu_id=stu_id # def choose_course(self): # print('%s is choosing course'%self.name) # # class OldboyTeather(OldboyPeople): # # def __init__(self,name,age,sex,level): # OldboyPeople.__init__(self,name,age,sex) # self.level=level # # def score(self,stu,num):#让学生与老师交互 # stu.score=num#新建一个学生的信息 # print('老师[%s]为学生[%s]打分[%s]'%(self.name,stu.name,num)) # # stu1=OldboyStudent('猪哥',19,'male',1) # teal=OldboyTeather('egon',18,'male',10) # stu1.choose_course() # teal.score(stu1,99)#将学生对象传值,进行交互 # print(stu1.score) class Course: def __init__(self,name,period,price):#创建课程 self.name=name self.period=period self.price=price def tell_info(self):#查看课程信息 msg=''' 课程名:%s 课程周期:%s 课程价格:%s '''%(self.name,self.period,self.price) print(msg) class OldboyPeople: school='oldboy' def __init__(self,name,age,sex): self.name=name self.age=age self.sex=sex class Oldboystudent(OldboyPeople): def __init__(self,name,age,sex,stu_id): OldboyPeople.__init__(self,name,age,sex) self.stu_id=stu_id def choose_course(self): print('%s is choosing course'%self.name) class OldboyTeather(OldboyPeople): def __init__(self,name,age,sex,level): OldboyPeople.__init__(self,name,age,sex) self.level=level def score(self,stu,num): stu.score=num print('老师[%s]为学生[%s]打分[%s]'%(self.name,stu.name,num)) # 创造课程 python=Course('python全栈开发','5mons',3000) linux=Course('linux运维','5mons',8000) python.tell_info() linux.tell_info() # 创造学生与老师 stu1=Oldboystudent('猪哥',19,'male',1) teal=OldboyTeather('egon',18,'male',10) # 将学生和老师与课程对象组合、关联 stu1.course=python#新建学生cousre的信息与课程组合 teal.course=linux#新建老师cousre的信息与课程组合 stu1.course.tell_info()#通过课程对象查看课程信息 teal.course.tell_info()#通过课程对象查看课程信息
python面向对象组合
最新推荐文章于 2023-11-30 14:21:00 发布