组合
组合的定义:把一个类的对象变成另一个类的属性
此例中course1这个实例变成了teacher1中的属性了
class People: school = 'luffycity' def __init__(self, name, age): self.name = name self.age = age def teach(self): print('%s is teaching' % self.name) def study(self): print('%s is studying' % self.name) class Teacher(People): def __init__(self, name, age, work): super().__init__(name, age) self.work = work def teach(self): super(Teacher, self).teach() teacher1 = Teacher('alex', 28, 'teach') class Student(People): def __init__(self, name, age, work): super().__init__(name, age) self.work = work def study(self): super(Student, self).study() student1 = Student('gao', 23, 'study') class Course: def __init__(self, course_name, course_price): self.course_name = course_name self.course_price = course_price def func(self): print('课程名:%s, 课程价格:%s' % (self.course_name, self.course_price)) course1 = Course('python', 3000) teacher1.course = course1 # 将一个类的对象变为另一个类的属性 teacher1.course.func() print() 输出结果: 课程名:python, 课程价格:3000