zoukankan      html  css  js  c++  java
  • 组合

    组合的定义:把一个类的对象变成另一个类的属性

    此例中course1这个实例变成了teacher1中的属性了

    class People:
    
        school = 'luffycity'
    
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
        def teach(self):
            print('%s is teaching' % self.name)
    
        def study(self):
            print('%s is studying' % self.name)
    
    
    class Teacher(People):
        def __init__(self, name, age, work):
            super().__init__(name, age)
            self.work = work
    
        def teach(self):
            super(Teacher, self).teach()
    
    
    teacher1 = Teacher('alex', 28, 'teach')
    
    
    class Student(People):
        def __init__(self, name, age, work):
            super().__init__(name, age)
            self.work = work
    
        def study(self):
            super(Student, self).study()
    
    
    student1 = Student('gao', 23, 'study')
    
    
    
    class Course:
        def __init__(self, course_name, course_price):
            self.course_name = course_name
            self.course_price = course_price
    
        def func(self):
            print('课程名:%s, 课程价格:%s' % (self.course_name, self.course_price))
    
    
    course1 = Course('python', 3000)
    
    teacher1.course = course1       # 将一个类的对象变为另一个类的属性
    teacher1.course.func()
    print()
    
    
    输出结果:
    课程名:python, 课程价格:3000
  • 相关阅读:
    MySQL 实训篇
    MySQL 操作部分
    MySQL 数据库设计部分
    Python Excel及setuptool安装
    泛型? extents super
    js中立即执行
    js的闭包
    js作用域与作用域链
    js编译和执行顺序
    文件下载
  • 原文地址:https://www.cnblogs.com/huizaia/p/9667909.html
Copyright © 2011-2022 走看看