zoukankan      html  css  js  c++  java
  • Python-类的组合与重用

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

    组合指的是,在一个类中以另外一个类的对象作为数据属性,称为类的组合

    1.继承的方式

    通过继承建立了派生类与基类之间的关系,它是一种'是'的关系,比如白马是马,人是动物。

    当类之间有很多相同的功能,提取这些共同的功能做成基类,用继承比较好,比如老师是人,学生是人

    2.组合的方式

    用组合的方式建立了类与组合的类之间的关系,它是一种‘有’的关系,比如教授有生日,教授教python和linux课程,教授有学生s1、s2、s3...

    示例:继承与组合

    class People:
        def __init__(self,name,age,sex):
            self.name=name
            self.age=age
            self.sex=sex
    
    class Course:
        def __init__(self,name,period,price):
            self.name=name
            self.period=period
            self.price=price
        def tell_info(self):
            print('<%s %s %s>' %(self.name,self.period,self.price))
    
    class Teacher(People):
        def __init__(self,name,age,sex,job_title):
            People.__init__(self,name,age,sex)
            self.job_title=job_title
            self.course=[]
            self.students=[]
    
    
    class Student(People):
        def __init__(self,name,age,sex):
            People.__init__(self,name,age,sex)
            self.course=[]
    
    
    eg=Teacher('eg',18,'male','霸道金牌讲师')
    s1=Student('牛二',18,'female')
    
    python=Course('python','3mons',3000.0)
    linux=Course('python','3mons',3000.0)
    
    #为老师eg和学生s1添加课程
    eg.course.append(python)
    eg.course.append(linux)
    s1.course.append(python)
    
    #为老师eg添加学生s1
    egon.students.append(s1)
    
    
    #使用
    for obj in eg.course:
        obj.tell_info()
  • 相关阅读:
    .net core 经典面试题
    面试常问概念类问题
    常见 .net 面试题目
    Linux 最常用150个命令汇总
    .net core 国际化(web通用版)
    vim 命令合集
    解决Mariadb安装时的Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-qenllaxj/mysqlclient/报错
    正则表达式
    python中的JWT
    chapter2.3、react高阶组件,装饰器
  • 原文地址:https://www.cnblogs.com/zivli/p/9867677.html
Copyright © 2011-2022 走看看