类跟类之间没有共同点,但是有关联,所以要用组合来解决
例如:学校、老师、课程 ,它们是完全不同的事物,但是,学校有老师,老师教课程给学生,即有关联
class School: def __init__(self, name, addr): self.name = name self.addr = addr def re_student(self): print('%s正在招生'%self.name) class Teacher: def __init__(self,name, gender, age): self.name = name self.gender = gender self.age = age class Course: def __init__(self, name, price, period,school,teacher): self.name = name self.price = price self.period = period self.school = school #这里的school指实例或对象 self.teacher = teacher #这里的teacher指实例或对象 s1 = School('河南工业大学', '郑州') s2 = School('北京大学', '北京') s3 = School('上海大学', '上海') t1 = Teacher('卢明霞', 'woman','26') t2 = Teacher('乔某某','woman','58') t3 = Teacher('周某某', 'male', '21') msg = ''' 1 河南工业大学 2 北京大学 3 上海大学 ''' msg2 = ''' 1 卢明霞 2 乔某某 3 周某某 ''' while True: print(msg) menu = { '1':s1, '2':s2, '3':s3 } choice = input("请选择学校:") school_obj = menu[choice] print(msg2) menu2 = { '1':t1, '2':t2, '3':t3 } choice2 = input("请选择老师:") teacher_obj = menu2[choice2] name = input('课程名:') price = input('课程费用:') period = input('课程周期:') new_course = Course(name, price, period, school_obj, teacher_obj) print('课程[%s]属于%s%s'%(new_course.name, new_course.school.name, teacher_obj.name))