https://blog.csdn.net/death_include/article/details/89201789
https://zhuanlan.zhihu.com/p/28340924
https://www.jianshu.com/p/d9de3fc047ee
http://www.hongweipeng.com/index.php/archives/1065/?utm_source=tuicool&utm_medium=referral
http://www.cppcns.com/jiaoben/python/155536.html
https://www.zky.name/article/67.html
http://capturesoul.com/archives/8594
https://msd.misuland.com/pd/2884250137616452844
Parent.init(self) 与 super(Child, self).init() 的区别是什么?
super 理解成父类也是理所当然,python里其实指的是 MRO 中的下一个类!
super其实干了这件事,看这个答案:
def super(cls, inst):
mro = inst.class.mro() # Always the most derived class
return mro[mro.index(cls) + 1]
MRO 全称 Method Resolution Order,它代表了类继承的顺序。
super 是用来解决多重继承问题的,假设B C D 都是直接继承class A
class E(B, C, D):
def init(self):
# code…
如果E类的构造函数使用 super(E, self).init() 时,A类的构造函数会被执行一次,而用另一种方法,A类的构造函数会被执行多次。
在 MRO 中,基类永远出现在派生类后面,如果有多个基类,基类的相对顺序保持不变。
super()可以避免重复调用
如果childA基础Base, childB继承childA和Base,如果childB需要调用Base的 init ()方法时,就会导致 init ()被执行两次:
class Base(object):
def __init__(self):
print 'Base create'
class childA(Base):
def __init__(self):
print 'enter A '
Base.__init__(self)
print 'leave A'
class childB(childA, Base):
def __init__(self):
childA.__init__(self)
Base.__init__(self)
b = childB()
Base的 init ()方法被执行了两次
enter A
Base create
leave A
Base create
使用super()是可避免重复调用
class Base(object):
def __init__(self):
print 'Base create'
class childA(Base):
def __init__(self):
print 'enter A '
super(childA, self).__init__()
print 'leave A'
class childB(childA, Base):
def __init__(self):
super(childB, self).__init__()
b = childB()
print b.__class__.mro()
enter A
Base create
leave A
[<class '__main__.childB'>, <class '__main__.childA'>, <class '__main__.Base'>, <type 'object'>]