zoukankan      html  css  js  c++  java
  • python课堂整理36-----组合

    类跟类之间没有共同点,但是有关联,所以要用组合来解决

    例如:学校、老师、课程 ,它们是完全不同的事物,但是,学校有老师,老师教课程给学生,即有关联

    class School:
        def __init__(self, name, addr):
            self.name = name
            self.addr = addr
    
        def re_student(self):
            print('%s正在招生'%self.name)
    
    class Teacher:
        def __init__(self,name, gender, age):
            self.name = name
            self.gender = gender
            self.age = age
    
    
    
    class Course:
        def __init__(self, name, price, period,school,teacher):
            self.name = name
            self.price = price
            self.period = period
            self.school = school  #这里的school指实例或对象
            self.teacher = teacher  #这里的teacher指实例或对象
    
    
    s1 = School('河南工业大学', '郑州')
    s2 = School('北京大学', '北京')
    s3 = School('上海大学', '上海')
    t1 = Teacher('卢明霞', 'woman','26')
    t2 = Teacher('乔某某','woman','58')
    t3 = Teacher('周某某', 'male', '21')
    
    msg = '''
    1 河南工业大学
    2 北京大学
    3 上海大学
    '''
    msg2 = '''
    1 卢明霞
    2 乔某某
    3 周某某
    '''
    while True:
        print(msg)
        menu = {
            '1':s1,
            '2':s2,
            '3':s3
        }
    
        choice = input("请选择学校:")
        school_obj = menu[choice]
        print(msg2)
        menu2 = {
            '1':t1,
            '2':t2,
            '3':t3
        }
        choice2 = input("请选择老师:")
        teacher_obj = menu2[choice2]
    
        name = input('课程名:')
        price = input('课程费用:')
        period = input('课程周期:')
    
        new_course = Course(name, price, period, school_obj, teacher_obj)
        print('课程[%s]属于%s%s'%(new_course.name, new_course.school.name, teacher_obj.name))
    

      

    一个奋斗中的产品小白
  • 相关阅读:
    Single Number 解答
    Minimum Size Subarray Sum 解答
    Valid Anagram 解答
    Count Primes 解答
    fullCalendar 日历显示每天数据调用方法实践
    jqGrid列的统计
    关于 asp.net Web Api 上传文件请求内容过大404错误记录
    My97DatePicker只显示月份
    js 宏微任务执行顺序
    git 等官网下载慢方法
  • 原文地址:https://www.cnblogs.com/dabai123/p/11451601.html
Copyright © 2011-2022 走看看