(6)组合

继承是解决类与类之间代码冗余的问题(冗余就是重复也是一种强耦合)

另一种方案就是

组合(解耦合)

组合也是解决类与类之间代码冗余问题的方案

 

组合: 某一个类的对象具备一个属性,该属性的值是另外一个类的对象
class OldboyPeople:
school = 'Oldboy'

def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender

class Course:#课程类
def __init__(self,name,price,period):
self.name = name
self.price = price
self.period = period

def tell_info(self):
print('<name:%s price:%s period:%s>' %(self.name,self.price,self.period))

class OldboyStudent(OldboyPeople):
def choose_course(self):
print('%s is choosing course' %self.name)

class OldboyTeacher(OldboyPeople):
def __init__(self, name, age, gender,level):
super().__init__(name, age, gender) #重用一下父类的功能,只要将和父类相同参数传入即可
self.level=level

def score(self,stu,num):
stu.score=num
print('老师[%s]为学生[%s]打了分[%s] ' %(self.name,stu.name,num))

python_obj=Course('python自动化开发',10000,'3mons')
linux_obj=Course('linux架构',20000,'2mons')

stu1=OldboyStudent('王大炮',18,'male',)
tea1=OldboyTeacher('Egon',18,'male',10)
print(stu1.__dict__)
print(tea1.__dict__)
*** stu1.course=python_obj #让学生1的课程类也传入python_obj的参数,初始化课程 ***
PS:让stu1的对象具备某一个属性,这个属性的值是也是一个对象,但是这个对象来自于另一个类,这就是组合

学生有可能选修多门课
stu1.courses=[] #这里学生课程就直接组合成一个列表
tea1.courses=[]
stu1.courses.append(python_obj) #然后将需要的课程直接放入列表
stu1.courses.append(linux_obj)
查看学生选修的课程
print(stu1.courses)
for obj in stu1.courses:
obj.tell_info() #obj下有一个tell_info方法,直接可以看到相关的课程

 


print(stu1.course.name) #属性course,这个属性的值是couse类对象
print(stu1.course.price)
print(stu1.course.period)
stu1.course.tell_info()
PS:对象自己类下和父类、里的属性和函数都能够读取到PS:类就是一个高度整合的东西,相互之间有继承,也可以靠组合整合到一起,相互获取属性和函数

 

posted @ 2018-12-09 20:54  clyde_S  阅读(163)  评论(0编辑  收藏  举报