Object Oriented Programming composition
Definition: an object have another one or more other objects properties and methods .
Effects: reduce code redundancy, decouple
关于耦合度的说明
耦合:通俗地讲,就是相互作用,相互影响的意思
耦合度越高,程序的可扩展性越低;
耦合度越低,程序的可扩展性越高。
And a combination of inherited differences
Portfolio: the relationship between the object and the object , understood as " what what " relationship
Inheritance: the relationship between class and class, subclass inherits the parent class attribute is "slave" relationship, that "what is" relationship.
class Course:
"""课程类"""
def __init__(self, course_name, course_price, course_duration):
"""课程名称,课程价格,课程时长"""
self.course_name = course_name
self.course_price = course_price
self.course_duration = course_duration
def show_course(self):
"""输出课程信息"""
print(f"""
========课程信息========
课程名称:{self.course_name}
课程价格:{self.course_price}
课程时长:{self.course_duration}
""")
class Student:
"""学生类"""
def __init__(self, name, age, gender):
"""姓名,年龄,性别"""
self.name = name
self.age = age
self.gender = gender
self.course_list = []
def add_course(self, course_obj):
"""增加课程"""
self.course_list.append(course_obj)
# 使用了Course类的course_name 属性
print(f"课程{course_obj.course_name}添加成功!")
def show_all_course(self):
"""显示学生课程表中所有课程信息"""
for course in self.course_list:
# 使用了Course类的show_course() 方法
course.show_course()
# 创建学生对象
stu = Student("dawn", 27, "男")
# 创建课程对象
python_obj = Course("python", 28888, 6)
go_obj = Course("go", 77777, 5)
# 将课程添加到学生对象中
stu.add_course(python_obj)
stu.add_course(go_obj)
# 打印学生中所有的课程表信息
stu.show_all_course()
Output
课程python添加成功!
课程go添加成功!
========课程信息========
课程名称:python
课程价格:28888
课程时长:6
========课程信息========
课程名称:go
课程价格:77777
课程时长:5