Python 继承中 super 运用

测试 1

代码段

#!/usr/bin/env python
# -*- coding: utf-8 -*-

class ChildA(object):
  def foo(self):
    print '--ChildA--'

class ChildB(ChildA):
  def foo(self):
    print '--ChildB--'
    super(ChildB, self).foo()

class ChildC(ChildA):
  def foo(self):
    print '--ChildC--'
    # super(ChildC, self).foo()

class ChildD(ChildB, ChildC):
  def foo(self):
    print '--ChildD--'
    super(ChildD, self).foo()

ChildD().foo()

执行结果如下

--ChildD--
--ChildB--
--ChildC--

测试 2

代码段

#!/usr/bin/env python
# -*- coding: utf-8 -*-

class ChildA(object):
  def foo(self):
    print '--ChildA--'

class ChildB(ChildA):
  def foo(self):
    print '--ChildB--'
    super(ChildB, self).foo()

class ChildC(ChildA):
  def foo(self):
    print '--ChildC--'
    super(ChildC, self).foo()

class ChildD(ChildB, ChildC):
  def foo(self):
    print '--ChildD--'
    super(ChildD, self).foo()

ChildD().foo()

执行结果如下

--ChildD--
--ChildB--
--ChildC--
--ChildA--

测试 3

代码段

#!/usr/bin/env python
# -*- coding: utf-8 -*-

class ChildA(object):
  def foo(self):
    print '--ChildA--'

class ChildB(ChildA):
  def foo(self):
    print '--ChildB--'
    # super(ChildB, self).foo()

class ChildC(ChildA):
  def foo(self):
    print '--ChildC--'
    super(ChildC, self).foo()

class ChildD(ChildB, ChildC):
  def foo(self):
    print '--ChildD--'
    super(ChildD, self).foo()

ChildD().foo()

执行结果如下

--ChildD--
--ChildB--

测试 4

代码段

#!/usr/bin/env python
# -*- coding: utf-8 -*-

class ChildA(object):
  def foo(self):
    print '--ChildA--'

class ChildB(ChildA):
  def foo(self):
    print '--ChildB--'
    # super(ChildB, self).foo()

class ChildC(ChildA):
  def foo(self):
    print '--ChildC--'
    # super(ChildC, self).foo()

class ChildD(ChildB, ChildC):
  def foo(self):
    print '--ChildD--'
    super(ChildD, self).foo()

ChildD().foo()

执行结果如下

--ChildD--
--ChildB--

问题提出

比较上面的结果,super 是怎么影响 mro 的呢

阅读 6k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进