面向物件-組合
阿新 • • 發佈:2018-12-31
組合:
學生有課程:stu.course1=python (stu 與 python都是例項化物件,course1 是變數名,可以變化)
學生有生日:stu.brith=d (stu與d 是例項化的物件,brith是變數名,可以根據意思寫其他的)
class People: school = 'luffycity' def __init__(self, name, age, sex): self.name = name self.age = age self.sex = sex class Teacher(People):def __init__(self, name, age, sex, level, salary): # People.__init__(self, name, age, sex) super().__init__(name, age, sex) self.level = level self.salary = salary def teach(self): print("%s teaching " % self.name) class Student(People): def __init__(self, name, age, sex, class_time): # People.__init__(self, name, age, sex) super().__init__(name, age, sex) self.class_time = class_time def learn(self): print("%s learing" % self.name) class Course: def __init__(self, course_name, course_price, course_period): self.course_name= course_name self.course_price = course_price self.course_period = course_period def tell(self): print("課程名稱 <%s> 課程價格 <%s> 課程時期<%s>" % (self.course_name, self.course_price, self.course_period)) class Date: def __init__(self,year,month,day): self.year=year self.month=month self.day=day def tell_info(self): print("%s-%s-%s"%(self.year,self.month,self.day)) d=Date(2018,12,10) s1=Student('mak',18,'male','2018/12/10') s1.brith=d s1.brith.tell_info() t1 = Teacher('alex', 28, '男', 'A', '10') t2 = Teacher('engo', 29, '男', 'A', '30') s1 = Student('may', '18', '男', '2018/12/10') s2 = Student('eric', '21', '男', '2018/12/10') python = Course('python', '300', '3months') linux = Course('linux', '400', '4months') t1.course = python # 先增加上課程這一項 print(t1.course.course_name) # 再取course的細項 print(t1.course.course_price) print(t1.course.course_period) t2.course=linux #先增加上課程這一項 print(t2.course.__dict__) #再調取course的細項 s1.course = python print(s1.course.course_name) print(s1.course.course_price) print(s1.course.course_period) s1.course = python # 想要組合其他專案;要先增加這項 s2.course2=linux s1.course.tell() s2.course2.tell() s1.courses = [] s1.courses.append(python) s1.courses.append(linux)