• 组合


    1.什么是组合?

    组合就是一个类的对象具备某一个属性,该属性的值是指向另外一个类的对象

    2.为何用组合?

    组合也是用来解决类与类之间代码冗余问题的。

    3.如何用组合?

    例子一:

    class OldboyPeople:
    school = 'oldboy'

    def __init__(self, name, age, sex):
    self.name = name
    self.age = age
    self.sex = sex

    class OldboyStudent(OldboyPeople):
    def __init__(self,name,age,sex,stu_id):
    OldboyPeople.__init__(self,name,age,sex)
    self.stu_id=stu_id

    def choose_course(self):
    print('%s is choosing course' %self.name)

    class OldboyTeacher(OldboyPeople):

    def __init__(self, name, age, sex, level):
    OldboyPeople.__init__(self,name,age,sex)
    self.level=level

    def score(self,stu,num):
    stu.score=num
    print('老师[%s]为学生[%s]打分[%s]' %(self.name,stu.name,num))


    stu1=OldboyStudent('猪哥',19,'male',1)
    tea1=OldboyTeacher('egon',18,'male',10)

    stu1.choose_course()
    tea1.score(stu1,100)
    print(stu1.__dict__)


    例二:

    用组合的方式,查看学生的课程的详细信息

    class Course:     #课程不是所有的oldboy里的人都需要选的,所以单独摘出来
    def __init__(self,name,period,price): #定制自己独有的属性
    self.name=name
    self.period=period
    self.price=price

    def tell_info(self): #选择课程之后才能查看课程信息,所以不放在oldboy,学生,老师类中,因为造出那个类的时候,还没选课程
    msg="""
    课程名:%s
    课程周期:%s
    课程价钱:%s
    """ %(self.name,self.period,self.price)
    print(msg)

    class OldboyPeople:
    school = 'oldboy'

    def __init__(self, name, age, sex):
    self.name = name
    self.age = age
    self.sex = sex

    class OldboyStudent(OldboyPeople):
    def __init__(self,name,age,sex,stu_id):
    OldboyPeople.__init__(self,name,age,sex) #用类名.函数名的方法重用父类
    self.stu_id=stu_id

    def choose_course(self):
    print('%s is choosing course' %self.name)

    class OldboyTeacher(OldboyPeople):

    def __init__(self, name, age, sex, level):
    OldboyPeople.__init__(self,name,age,sex)
    self.level=level

    def score(self,stu,num):
    stu.score=num
    print('老师[%s]为学生[%s]打分[%s]' %(self.name,stu.name,num))

    # 创造课程
    python=Course('python全栈开发','5mons',3000)
    linux=Course('linux运维','5mons',800)
    # python.tell_info()
    # linux.tell_info()


    # 创造学生与老师
    stu1=OldboyStudent('猪哥',19,'male',1)
    tea1=OldboyTeacher('egon',18,'male',10)


    # 将学生、老师与课程对象关联/组合
    stu1.course=python #学生对象.属性的值指向课程类的对象,学生对象就可以引用课程类的各种数据以及函数功能,就可以查看信息了
    tea1.course=linux

    stu1.course.tell_info() ##学生对象.属性的值指向课程类的对象,学生对象就可以引用课程类的各种数据以及函数功能,就可以查看信息了
    tea1.course.tell_info()





  • 相关阅读:
    第四次作业
    第三次作业
    Java.14
    Java.13
    JAVA.12
    JAVA.11
    JAVA.10
    JAVA.9
    JAVA.8
    JAVA.7
  • 原文地址:https://www.cnblogs.com/fxc-520520/p/9234074.html
Copyright © 2020-2023  润新知