【python】继承问题-深度、广度优先

python super()
http://www.cnblogs.com/lovemo1314/archive/2011/05/03/2035005.html
这篇文章介绍了super的用法,我看了这段代码不懂:

class A(object):
  def __init__(self):
   print "enter A"
   print "leave A"

 class B(object):
  def __init__(self):
   print "enter B"
   print "leave B"

 class C(A):
  def __init__(self):
   print "enter C"
   super(C, self).__init__()
   print "leave C"

 class D(A):
  def __init__(self):
   print "enter D"
   super(D, self).__init__()
   print "leave D"
 class E(B, C):
  def __init__(self):
   print "enter E"
   B.__init__(self)
   C.__init__(self)
   print "leave E"

 class F(E, D):
  def __init__(self):
   print "enter F"
   E.__init__(self)
   D.__init__(self)
   print "leave F"

f = F() result:

 enter F
 enter E
 enter B
 leave B
 enter C
 enter D
 enter A
 leave A
 leave D
 leave C
 leave E
 enter D
 enter A
 leave A
 leave D
 leave F

为什么多了一层d
在输出的第六行为何多了enter d
和我想象的不一样:

【python】继承问题-深度、广度优先_第1张图片
C2{QYV~BBNDMBJ2W$29@9~T.jpg

文章里说,
mro中记录了一个类的所有基类的类类型序列。查看mro的记录,发觉包含7个元素,7个类名分别为:
F E B C D A object
“从而说明了为什么在C.init中使用super(C, self).init()会调用类D的初始化函数了。 ???”

代码改成:

class A(object):
  def __init__(self):
   print "enter A"
   super(A, self).__init__()  # new
   print "leave A"

 class B(object):
  def __init__(self):
   print "enter B"
   super(B, self).__init__()  # new
   print "leave B"

 class C(A):
  def __init__(self):
   print "enter C"
   super(C, self).__init__()
   print "leave C"

 class D(A):
  def __init__(self):
   print "enter D"
   super(D, self).__init__()
   print "leave D"
 class E(B, C):
  def __init__(self):
   print "enter E"
   super(E, self).__init__()  # change
   print "leave E"

 class F(E, D):
  def __init__(self):
   print "enter F"
   super(F, self).__init__()  # change
   print "leave F"

f= F():

 enter F
 enter E
 enter B
 enter C
 enter D
 enter A
 leave A
 leave D
 leave C
 leave B
 leave E
 leave F

看不懂也。

立个flag
需要搞懂的有:
经典类和新式类
MRO算法
多态继承
深度优先和广度优先

你可能感兴趣的:(【python】继承问题-深度、广度优先)