类的组合,即在类实例化时,将另一个类的实例作为参数传入,这样可以将两个实例关联起来。
class course: def __init__(self,name,price,period,teacher): self.name=name self.price=price self.period=period self.teacher=teacher class teacher: def __init__(self,name,sex): self.name=name self.sex=sex class student: def __init__(self,name,age,course): self.name=name self.age=age self.course=course t1=teacher('Bob',38) t2=teacher('Jack',45) t3=teacher('Jane',45) c1=course('python',6000,'3 months',t2)#将teacher作为参数传递给课程实例 c2=course('linux',7000,'5 months',t1) c3=course('mysql',6500,'5 months',t3) d={'1':c1,'2':c2,'3':c3} name='Alice' age=21 while True: choice=input('please choice course:') if choice in d.keys(): s1=student(name,age,d[choice])#将课程实例作为参数传递给学生实例 print(s1.__dict__) print('%s choose course %s,%s is the teacher'%(s1.name,s1.course.name,s1.course.teacher.name)) elif int(choice)==0: exit(0) else: print('please input correct choice')