面向對象之組合
阿新 • • 發佈:2018-09-04
方式 main geo pan 周期 北京 int zha dict
1、組合模式
class Hand: pass class Foot: pass class Trunk: pass class Head: pass class Person: def __init__(self,id_num,name): self.id_num=id_num self.name=name self.hand=Hand() self.foot=Foot() self.trunk=Trunk() self.head=Head() p1=Person(‘111111‘,‘alex‘)
2、組合練習
class School: def __init__(self,name,addr): self.name=name self.addr=addr def zhao_sheng(self): print(‘%s 正在招生‘%self.name) class Course: def __init__(self,name,price,period,school): self.name=name self.price=price self.period=period self.school=school s1=School(‘oldboy‘,‘北京‘) s2=School(‘oldboy‘,‘南京‘) s3=School(‘oldboy‘,‘東京‘) c1=Course(‘linux‘,10,‘1h‘,s1) print(c1.__dict__) #{‘name‘: ‘linux‘, ‘price‘: 10, ‘period‘: ‘1h‘, ‘school‘: <__main__.School object at 0x000001BD46E57BE0>}print(c1.school.name)#oldboy
3、組合練習升級
class School: def __init__(self,name,addr): self.name=name self.addr=addr def zhao_sheng(self): print(‘%s 正在招生‘%self.name) class Course: def __init__(self,name,price,period,school,teacher): self.name=name self.price=price self.period=period #組合的方式建關聯 self.school=school self.teacher=teacher class Teacher: def __init__(self,name,age,sex,school): self.name=name self.age=age self.sex=sex self.school=school def tea_stu(self): print(‘%s 老師正在上課‘%self.name) s1=School(‘oldboy‘,‘北京‘) s2=School(‘oldboy‘,‘南京‘) s3=School(‘oldboy‘,‘東京‘) # c1=Course(‘linux‘,10,‘1h‘,s1) msg=‘‘‘ 1 老男孩 北京校區 2 老男孩 南京校區 3 老男孩 東京校區 ‘‘‘ while True: print(msg) menu={ ‘1‘:s1, ‘2‘:s2, ‘3‘:s3, } choice=input(‘選擇學校>>: ‘).strip() school_obj=menu[choice] t1=Teacher(‘alex‘,18,‘male‘,school_obj) t2=Teacher(‘egon‘,22,‘male‘,school_obj) t3=Teacher(‘shanshan‘,35,‘female‘,school_obj) msg1=‘‘‘ 1 alex老師 2 geon老師 3 shanshan老師 ‘‘‘ print(msg1) menu1={ ‘1‘:t1, ‘2‘:t2, ‘3‘:t3, } tea_name=input(‘選擇代課老師的姓名>>: ‘).strip() teacher_obj=menu1[tea_name] name=input(‘課程名>>: ‘).strip() price=input(‘課程費用>>: ‘).strip() period=input(‘課程周期>>: ‘).strip() new_course=Course(name,price,period,school_obj,teacher_obj) print(‘‘‘ ------------選課詳細信息------------ 學校:%s 地址:%s 老師:%s 年齡:%s 性別%s 課程:%s 費用:%s 周期:%s ‘‘‘%(new_course.teacher.school.name,new_course.teacher.school.addr,new_course.teacher.name,new_course.teacher.age,new_course.teacher.sex,new_course.name,new_course.price,new_course.period))
2018-09-03 22:05:57
面向對象之組合