模拟组合的应用场景

xiaoxiao2021-02-28  44

""" 老师 ‘是’ 人 ==》继承 老师 ‘有’ 课程 ==》组合 """ 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, ): super().__init__(name, age, sex) self.level = level self.salary = salary def teach(self): print('%s is teaching' % self.name) class Student(People): def __init__(self, name, age, sex, class_time, ): super().__init__(name, age, sex) self.class_time = class_time def learn(self): print('%s is learning' % 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_info(self): print('课程名<%s> 课程价钱<%s> 课程周期<%s>' % (self.course_name, self.course_price, self.course_period)) class Date: def __init__(self, year, mon, day): self.year = year self.mon = mon self.day = day def tell_info(self): print('%s-%s-%s' % (self.year, self.mon, self.day)) # teacher1=Teacher('alex',18,'male',10,3000,) # 创建老师对象 # teacher2=Teacher('egon',28,'male',30,3000,) # python=Course('python',3000,'3mons') # 创建课程对象 # linux=Course('linux',2000,'4mons') # # # print(python.course_name) # 打印对象属性 # # teacher1.course=python # 将实例老师增加属性。属性为对象:python # teacher2.course=python # # print(python) # python的对象地址 # print(teacher1.course) # 调用实例老师的新增属性course # print(teacher2.course) # print(teacher2.__dict__) # # # {'sex': 'male', 'level': 30, 'salary': 3000, 'name': 'egon', 'course': <__main__.Course object at 0x000000000A5ACD68>, 'age': 28} # # 此时增加了属性course。值是一个内存地址 # # print(teacher1.course.course_name) # # print(teacher2.course.course_name) # teacher1.course.tell_info() # student1=Student('张三',28,'female','08:30:00') # student1.course1=python # student1.course2=linux # student1.course1.tell_info() # student1.course2.tell_info() # student1.courses=[] # 使用列表格式 # student1.courses.append(python) # student1.courses.append(linux) student1 = Student('张三', 28, 'female', '08:30:00') d = Date(1988, 4, 20) python = Course('python', 3000, '3mons') student1.birth = d student1.birth.tell_info() student1.course = python student1.course.tell_info() print(student1.__dict__) # {'class_time': '08:30:00', 'course': <__main__.Course object at 0x000000000A5AC7B8>, 'sex': 'female', 'age': 28, 'birth': <__main__.Date object at 0x000000000A5AC6D8>, 'name': '张三'}
转载请注明原文地址: https://www.6miu.com/read-2621441.html

最新回复(0)