day21_组合
目录
组合
组合指的是将一个对象作为另一个对象的属性
目的是为了减少代码冗余,增加程序扩展性
class Student:
def __init__(self, name, age, id):
self.name = name
self.age = age
self.id = id
self.course_list = []
# 对象的组合
def choose_course(self, course_obj):
self.course_list.append(course_obj)
def my_courses_info(self):
print(f'学生:{self.name}')
for course_obj in self.course_list:
course_obj.print_course_info()
class Course:
def __init__(self, course_name, course_period, course_price):
self.course_name = course_name
self.course_period = course_period
self.course_price = course_price
def print_course_info(self):
print(f'''
课程名称:{self.course_name}
课程时长:{self.course_period}
课程价格:{self.course_price}''')
# 实例化
student1 = Student('小明', 18, 19101101)
student2 = Student('小红', 18, 19101102)
python = Course('python', 6, 2.3)
linux = Course('linux', 4, 1.2)
student1.choose_course(python)
student2.choose_course(python)
student2.choose_course(linux)
student1.my_courses_info()
student2.my_courses_info()