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 的呢
user君
9 years, 4 months ago