python基础 类(四) 类的多继承
前言
接上篇单继承,这篇写写多继承的执行顺序
菱形结构的多继承
class AAA:
def __init__(self):
print('AAAinit')
print('over AAA init')
#print('AAA init ! ' + str(class_num))
#self.class_num = class_num
def talk_to_all(self):
print("I am AAA!")
class A(AAA):
#def __init__(self, class_num, *args):
def __init__(self):
print('A init')
super().__init__()
print('over A init')
'''
print('A init ! ' + str(class_num))
print('A init ! ' + str(args))
super(A, self).__init__(*args)
self.class_num = class_num
'''
def talk_to_all(self):
print("I am A!")
class B(AAA):
#def __init__(self, class_num, *args):
def __init__(self):
print('B init')
super().__init__()
print('over B init')
'''
print('B init ! ' + str(class_num))
print('B init ! ' + str(args))
super(B, self).__init__(*args)
self.class_num = class_num
'''
def talk_to_all(self):
print("I am B!")
class C(A, B):
#def __init__(self, class_num, *args):
def __init__(self):
print('C init')
super().__init__()
print('over c init')
'''
print("C Init ! " + str(class_num))
print('C init ! ' + str(args))
super(C, self).__init__(*args)
self.class_num = class_num
'''
def talk_to_all(self):
print("==== I am C! ====")
super(B, self).talk_to_all()
test = C()
#test.talk_to_all()
print(C.__mro__)
执行结果
普通多继承
class A:
#def __init__(self, class_num, *args):
def __init__(self):
print('A init')
#super().__init__()
print('over A init')
def talk_to_all(self):
print("I am A!")
class B:
#def __init__(self, class_num, *args):
def __init__(self):
print('B init')
#super().__init__()
print('over B init')
def talk_to_all(self):
print("I am B!")
class C(A, B):
#def __init__(self, class_num, *args):
def __init__(self):
print('C init')
super().__init__()
print('over c init')
def talk_to_all(self):
print("==== I am C! ====")
super(B, self).talk_to_all()
test = C()
print(C.__mro__)
执行结果
可知,在多继承时,只是执行了第一个父类的构造函数
上面两种继承时执行的原型链