類的組合
學校與課程沒有共同點,課程與老師沒有共同點,可是學校與課程有關聯,課程與老師有關聯;學校、課程、老師是三個徹底不一樣的類;課程是屬於學校的,老師是教課程的,此時咱們就用到類的組合來關聯,學校-課程,課程-老師;html
class School: """ 學校類 """ def __init__(self,name,address): self.name = name self.address = address class Course: """ 課程類 """ def __init__(self,name,price,period,school): self.name = name self.price = price self.period = period self.school = school class Teacher: """ 老師類 """ def __init__(self,name,gender,age,course): self.name = name self.gender = gender self.age = age self.course = course #學校實例化 x1 = School("oldboy","北京校區") x2 = School("oldboy","天津校區") x3 = School("oldboy","南京校區") #課程實例化 k1 = Course("python",19880,"6個月",x1) #課程與學校關聯 k2 = Course("linux",17880,"4個月",x2) k3 = Course("go",20000,"8個月",x3) #教師實例化 j1 = Teacher("alex","male",34,k2) #教師與課程關聯 j2 = Teacher("武sir","male",30,k1) j3 = Teacher("林海峯","male",35,k3) print(k1.__dict__) print(k1.school.name) print(j1.__dict__) print(j1.course.name)