1.什么是组合?
组合指的是某一个对象拥有一个属性,该属性是另一个类的对象
1 class Foo: 2 pass 3 4 class Bar: 5 pass 6 7 obj=Foo() 8 obj.attr=Bar() 9 10 obj.xxx 11 obj.attr.yyy
2.为什么要使用组合?
通过为某一个对象添加属性(属性的值是另外一个类的对象)的方式,可以间接地将两个类关联/整合/组合到一起
从而减少类与类之间代码冗余
1 class Foo1: 2 pass 3 class Foo2: 4 pass 5 class Foo3: 6 pass 7 8 class Bar: 9 pass 10 11 obj_from_bar=Bar() 12 13 obj1=Foo1() 14 obj2=Foo2() 15 obj3=Foo3() 16 17 obj1.attr1=obj_from_bar 18 obj2.attr2=obj_from_bar 19 obj3.attr3=obj_from_bar
3.怎么使用组合
1 class OldboyPeople: 2 school = 'Oldboy' 3 4 def __init__(self,name,age,sex,): 5 self.name = name 6 self.age = age 7 self.sex = sex 8 9 class OldboyStudent(OldboyPeople): 10 def __init__(self, name, age, sex,score=0): 11 OldboyPeople.__init__(self,name,age,sex) 12 self.score = score 13 self.courses=[] 14 15 def choose_course(self): 16 print('%s choosing course' % self.name) 17 18 def tell_all_course(self): 19 print(('学生[%s]选修的课程如下' %self.name).center(50,'=')) 20 for obj in self.courses: 21 obj.tell_info() 22 print('='*60) 23 24 class OldboyTeacher(OldboyPeople): 25 def __init__(self,name,age,sex,level): 26 OldboyPeople.__init__(self,name,age,sex) 27 self.level=level 28 self.courses=[] 29 30 def score(self,stu,num): 31 stu.score=num 32 33 def tell_all_course(self): 34 print(('老师[%s]教授的课程如下' %self.name).center(50,'*')) 35 for obj in self.courses: 36 obj.tell_info() 37 print('*'*70) 38 39 class Course: 40 def __init__(self,c_name,c_price,c_period): 41 self.c_name = c_name 42 self.c_price = c_price 43 self.c_period = c_period 44 45 def tell_info(self): 46 print('<课程名:%s 价钱:%s 周期:%s>' %(self.c_name,self.c_price,self.c_period)) 47 48 # 创建课程对象 49 python=Course('python全栈开发',1900,'5mons') 50 linux=Course('linux架构师',900,'3mons') 51 52 53 stu1=OldboyStudent('刘二蛋',38,'male') 54 stu1.courses.append(python) 55 stu1.courses.append(linux) 56 # print(stu1.courses) 57 stu1.tell_all_course() 58 59 60 tea1=OldboyTeacher('egon',18,'male',10) 61 tea1.courses.append(python) 62 # print(tea1.courses) 63 tea1.tell_all_course()