Chapter XI compositions such object-oriented

Chapter XI compositions such object-oriented

First, what is a combination of

Is a combination of an object class includes a single property, the value of this attribute is another object of the class

Second, why use a combination of

  • Redundant code combinations are used to solve the problem between the class and class

  • Requirements: If we need to add properties courses to students, but it is not all old boy students had entered the school curriculum properties, property courses to students after the old boy elected, that is to say the latter course requires students added to it

  • Realization of ideas: if we add properties directly in the student curriculum, then students will need to add courses just been defined properties, which do not meet our requirements, so we can use in the future to add a combination of properties allows students to courses

  • class People():
        def __init__(self,name,age):
            self.name=name
            self.age=age
    
    class Student(People):
        def __init__(self,name,age):
            self.course_list=[]
            super().__init__(name,age)
    
        def choose_course(self,course):
            self.course_list.append(course)
    
    class Course():
        def __init__(self,course_name,course_price):
            self.name=course_name
            self.price=course_price
    
    course=Course('语文',20000)#先给生成的course对象赋值
    student1=Student('ypp',18)#生成一个学生对象
    student1.choose_course(course)#把course对象传到student的choose_course()方法
    
    for course in student1.course_list:
        print(course.name)
    print(student1.__dict__)
    ---------------------------------------------------
    语文
    ------------------------------------------------
    {'course_list': [<__main__.Course object at 0x0000016A4928EE48>], 'name': 'ypp', 'age': 18}
    #可见student1参数可以存放对象

Guess you like

Origin www.cnblogs.com/demiao/p/11425611.html