组合
在一个类中以另外一个类的对象作为数据属性,称为类的组合。
组合和继承都是有效利用已有类的资源的重要方式。区别:
继承:通过继承建立了派生类和基类之间的关系,是一种“是”的关系。当类之间有很多相同的功能,提取这些共同的功能做成基类,用继承比较好。例如:学生是人,老师是人。
组合:用组合的方式建立了类与组合之间的关系,是一种“有”的关系。例如:人有生日,老师有课程
当类之间有显著不同,并且较小的类是较大的类所需要的组件时,用组合比较好。
class People: school = "university" def __init__(self,name,age,sex): self.name = name self.age = age self.sex = sex class Teacher(People): # 继承 def __init__(self,name,age,sex,level,salary): super(Teacher, self).__init__(name,age,sex) self.level = level self.salary = salary def teach(self): print("%s is teaching"%self.name) class Student(People): def __init__(self, name, age, sex, class_time): super(Student, self).__init__(name,age,sex) self.class_time = class_time def learn(self): print("%s is learning" % self.name) class Course: def __init__(self,name,price,period): self.course_name = name self.course_price = price self.course_period = period def tell_info(self): print("课程名:%s,课程价钱:%s,课程周期:%s"%(self.course_name,self.course_price,self.course_period)) class Date(): def __init__(self,year,mon,day): self.year = year self.mon = mon self.day = day def tell_info(self): print("%s-%s-%s"%(self.year,self.mon,self.day)) # teacher1 = Teacher("alex",20,"male",10,3000) # python = Course("python",3000,"3months") # linux = Course("linux",2000,"4months") # # teacher1.course = python # 让老师有了一个属性,指向课程 # print(teacher1.course.course_name) # teacher1.course.tell_info() # # student = Student("张三",28,"female","8:00") # student.course1 = python # student.course2 = linux # student.course1.tell_info() # student.course2.tell_info() # student.courses=[] # student.courses.append(python) # student.courses.append(linux) # for i in student.courses: # print(i.__dict__) student = Student("张三",28,"female","8:00") d = Date(1988,4,20) student.birth = d # 组合 student.birth.tell_info()