继承与派生

继承:

  是一种新建的类型,新建的类称为子类/派生类,被继承的类称为父类/基类/超类

 

继承特性:

  (1)一个子类可以继承多个父类            class auth(a,b,c)

  (2)子类可以遗传父类的属性    

 

类分为两种:

  新式类:Python3 全是新式类,默认继承(object)

  经典类:python2中才有经典类,不会默认继承(object)      

 

继承的目的:

  减少类之间的代码冗余

 

利用继承来减少类代码冗余:

class Oldboy_people:

    school = 'Oldboy'

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

        self.name = name        

  self.age = age        

  self.sex = sex        

 

class Oldboy_student(Oldboy_people):

        def chouse(self):

        print('%s choosing course' %self.name)

 

class Oldboy_teacher(Oldboy_people):

        def score(self,stu,number):

          stu.sen = number

 

stu = Oldboy_student(18,'wxx','male') print(stu.__dict__)

tea = Oldboy_student(18,'zxx','male') print(tea.__dict__)

 

问题1:子类如何用父类的属性

问题2:属性查找顺序

  先从自己的对象里找,没有从自己的类里面去找,然后从自己的继承的父类去找,一直找到objact

问题3:新式类与经典类的属性查找的区别 (菱形继承) 

   (单线程)

    从对象开始,对象的类,继承的父类,一层层往上找,直到 object

  

    (多线程 没有共同继承一个 objact)

    从左往右一个分支分支查找

 

    (多线程 共同继承一个 objact)

    (1)新式类:广度优先查找        从左往右查找,最后再找最上面的父类

    (2)经典类:深度优先查找  第一条路一直找到最顶端的父类为止,在找第二条线

 

在子类派生出新方法,重用父类功能方式(一)

  # 指名道姓的引用某一个类中的函数,跟继承无关,该传多少参数,就传多少参数

  

在子类派生出新方法,重用父类功能方式(二)

  super()    必须在类中使用,专门用来访问父类中的属性,完全参照 mro 列表

  在python2 中   : super( 自己的类名,自己的对象)

  在python3 中   : super() 自动传参,不需要自己传参数

  

 

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, score=0):

        OldboyPeople.__init__(self,name,age,sex)       #直接调用类里面的函数

  super( OldboyStudent,self ).__init__(age,name,sex)         # super

        self.score = score

    def choose_course(self):

        print('%s choosing course' % self.name)

 

class OldboyTeacher(OldboyPeople):

    def __init__(self,name,age,sex,level):

        OldboyPeople.__init__(self,name,age,sex)     方式1

  super( ).__init__(age,name,sex)             super 自动传参

        self.level=level

    def score(self,stu,num):

        stu.score=num

 

stu1=OldboyStudent('刘二蛋',38,'male')

print(stu1.__dict__)

 

tea1=OldboyTeacher('egon',18,'male',10)

print(tea1.__dict__)

 

posted @ 2018-08-20 17:26  星牧  阅读(105)  评论(0编辑  收藏  举报