005---组合

组合与重用性

软件重用的方式除了继承还有另外一种,即组合。

  • 组合:在一个类中以另一个类的对象作为属性,称为组合。组合指的是一种什么有什么的关系。
    #! /usr/bin/env python
    # -*- coding: utf-8 -*-
    # __author__ = "ziya"
    # Date: 2018-08-26

    class Person:
        school = 'LuffyCity'
    
        def __init__(self, name, age, sex):
            self.name = name
            self.age = age
            self.sex = sex
    
    
    class Teacher(Person):
        school = 'LuffyCity'
    
        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(Person):
        school = 'LuffyCity'
    
        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_peroid):
            self.course_name = course_name
            self.course_price = course_price
            self.course_peroid = course_peroid
    
        def tell_info(self):
            print('课程名:%s  课程价钱:%s 课程周期:%s ' % (self.course_name, self.course_price, self.course_peroid))
    
    
    # 实例化两个教师
    t1 = Teacher('alex', 18, 'male', 10, 3000)
    t2 = Teacher('egon', 28, 'male', 8, 2000)
    # 实例化一个学生
    s1 = Student('张三', 28, 'famale', '8:30')
    # 实例化两门课程
    python = Course('Python', 8999, '6months')
    linux = Course('Linux', 6666, '3months')
    
    # 把Course的对象,python课程赋值给教师。代表教师教这么课程
    t1.course = python
    t2.course = python
    print('老师%s教的课的名称' % t1.name, t1.course.course_name)
    print('老师%s教的课的价格' % t2.name, t2.course.course_price)
    t1.course.tell_info()  
    
    s1.course = linux
    s1.course.tell_info()  
  • 总结:当类之间有显著不同,并且较小的类是较大的类的组件时候,用组合比较好。
原文地址:https://www.cnblogs.com/xjmlove/p/10321078.html