多重继承 即一个类继承自多个类,之后该类就可以拥有其父类的属性了

 

class Person(object):
    def __init__(self):
        print 'person'
class Teacher(Person):
    def __init__(self):
        super(Teacher, self).__init__()
        print 'teacher'
class Student(Person):
    def __init__(self):
        super(Student, self).__init__()
        print 'student'
class Ball(object):
    def __init__(self):
        print 'ball'
class Basketball(Ball):
    def __init__(self):
        super(Basketball, self).__init__()
        print 'basketball'
class Football(Ball):
    def __init__(self):
        super(Football, self).__init__()
        print 'football'
class One(Student, Basketball):
    def __init__(self):
        super(One, self).__init__()
        print '会篮球的学生'
class Two(Teacher, Football):
    def __init__(self):
        super(Two, self).__init__()
        print '会足球的老师'
one = One()
==> person
==> student
==> 会篮球的学生
two = Two()
==> person
==> teacher
==> 会足球的老师

以上例子的解读:Teacher与Student是Person的子类,Basketball与Football是Ball的子类。One继承自Student与Basketball;Two继承自Teacher与Football。所有的类中都有个名为__init__()的函数。

因为__init__()函数是在创建实例时自动调用的,所以在创建了One实例one时,系统自动调用One的__init__()函数,又因为类One继承自Student与Basketball,所以此时系统又会自动调用Student与Basketball的__init__()。在One类中,在写继承类时,书写顺序为Student、Basketball,在调用__init__()时顺序为先Student父类Person中的__init__(),又Student的__init__(),最后One中的__init__()。Basketball中的__init__()方法没有被调用。但如果调换Basketball与Student的顺序,就类One1的情况(下面有代码),此时只调用Basketball中的一系列类中的__init__()方法,顺序为自头向下。

class One1(Basketball, Student):
    def __init__(self):
        super(One1, self).__init__()
        print '会篮球的学生'
class Two2(Football, Teacher):
    def __init__(self):
        super(Two2, self).__init__()
        print '会足球的老师'
one1 = One1()
==> ball
==> basketball
==> 会篮球的学生
two2 = Two2()
==> ball
==> football
==> 会足球的老师

以上是父类与子类有同名方法的情况,没有同名方法时的情况是什么呢?即子类的实例对象能调用父类的方法,但父类不能访问子类的方法。

class Person(object):
    def p(self):
        print 'p'
class Teacher(Person):
    def t(self):
        print 't'
class Ball(object):
    def b(self):
        print 'b'
class Football(Ball):
    def f(self):
        print 'f'
class One(Teacher, Football):
    def o(self):
        print 't+f'
one = One()
one.o()
==> t+f
one.f()
==> f
one.t()
==> t
teacher = Teacher()
teacher.t()
==> t
teacher.p()
==> p
teacher.o()
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
AttributeError: 'Teacher' object has no attribute 'o'

感觉上面的内容有点乱 ><!      下面总结下:

多重继承中,父类子类有同名函数时:

  1. 子类的实例对象调用子类的该方法时,结果为:先输出父类的该函数内容,再输出子类的。若父类还有父类,即爷爷类(表达较搞笑,为了方便表达,理解理解哈),则先输出爷爷类的方法,再父类方法,最后子类方法。
  2. 子类中书写的继承类顺序,在子类实例对象调用其方法时,只能调用第一个继承类的一系列的该方法。(继承类的顺序我们按由左至右的顺序算的哈)

多重继承中,父类子类有不同名函数时:

  1. 子类的实例对象可以调用其自身的方法,也能调用父类的方法。
  2. 父类的实例对象不能调用其子类的方法。