zoukankan      html  css  js  c++  java
  • 继承与派生

    什么是继承

    继承是一种新建类的方式,新建的类称为子类,被继承的类称为父类
    继承的特性是:子类会遗传父类的属性
    强调:继承是类与类之间的关系

    为什么要用继承

    减少代码冗余

    怎样使用继承

    在python中支持一个类同时继承多个父类
    在python3中
    如果一个类没有继承任何类,那默认继承object类
    在python2中:
    如果一个类没有继承任何类,不会继承object类

    新式类
    但凡继承了object的类以及该类的子类,都是新式类
    经典类
    没有继承object的类以及该类的子类,都是经典类

    在python3中都是新式类,只有在python2中才区别新式类与经典类

    继承的应用

    派生:子类中新定义的属性,子类在使用时始终以自己的为准

    class OldboyPeople:
        school = 'oldboy'
        def __init__(self,name,age,sex):
            self.name = name #tea1.name='egon'
            self.age = age #tea1.age=18
            self.sex = sex #tea1.sex='male'
    
    
    
    class OldboyStudent(OldboyPeople):
        def choose_course(self):
            print('%s is choosing course' %self.name)
    
    
    class OldboyTeacher(OldboyPeople):
        #            tea1,'egon',18,'male',10
        def __init__(self,name,age,sex,level):
            # self.name=name
            # self.age=age
            # self.sex=sex
            OldboyPeople.__init__(self,name,age,sex)
            self.level=level
    
        def score(self,stu_obj,num):
            print('%s is scoring' %self.name)
            stu_obj.score=num
    
    stu1=OldboyStudent('耗哥',18,'male')
    tea1=OldboyTeacher('egon',18,'male',10)

    对象查找属性的顺序:对象自己-》对象的类-》父类-》父类...

    # print(stu1.school)
    # print(tea1.school)
    # print(stu1.__dict__)
    # print(tea1.__dict__)
    
    tea1.score(stu1,99)
    
    print(stu1.__dict__)
  • 相关阅读:
    输入属性,输出属性
    angular响应式表单
    angular 响应式表单指令
    c++ Primer
    CString 操作函数
    字符串分割strtok_s
    LPSTR LPTSTR
    CString分割切分
    CStringArray
    十进制
  • 原文地址:https://www.cnblogs.com/chillwave/p/9230867.html
Copyright © 2011-2022 走看看