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
  • 相关阅读:
    十步完全理解 SQL
    Oracle VM Virtual
    Pycharm 使用
    Open Yale course:Listening to Music
    SQL 必知必会
    安装 SQL server 2008 R2
    Ubuntu安装mysql之后,编译找不到头文件
    core dump文件的生成
    Linux静态库与动态库制作过程
    GEC6818连接Ubuntu,下载程序至开发板
  • 原文地址:https://www.cnblogs.com/huizaia/p/9667909.html
Copyright © 2011-2022 走看看