super调用父类的方法,对于单继承,父类很明显,不难理解,对于多继承,super的调用方法就不同了,2个例子搞懂多继承时,super调用父类方法
class A(object):
def __init__(self):
print "A.__init__"
class B(A):
def __init__(self):
A.__init__(self)
print "B.__init__"
class C(A):
def __init__(self):
A.__init__(self)
print "C.__init__"
class D(B,C):
def __init__(self):
B.__init__(self)
C.__init__(self)
print "D.__init__"
D()
print "\n"
# D()
# A.__init__
# B.__init__
# A.__init__
# C.__init__
# D.__init__
class A1(object):
def __init__(self):
print "A1.__init__"
class B1(A1):
def __init__(self):
super(B1, self).__init__()
print "B1.__init__"
class C1(A1):
def __init__(self):
super(C1, self).__init__()
print "C1.__init__"
class D1(B1,C1):
def __init__(self):
super(D1, self).__init__()
print "D1.__init__"
print "======================= super ==================\n"
print "D1.__mro__ \n",D1.__mro__
D1()
# D1()
# A1.__init__
# C1.__init__
# B1.__init__
# D1.__init__
运行之后发现,super的调用方式很奇怪,和我们想的不一样,后来看了《Python高级编程》之后,才明白原来super是按照类的__mro__属性里的基类的顺序来搜索父类的