为什么使用super()?
使用Base有区别吗__init__和super()__初始__?
class Base(object):
def __init__(self):
print "Base created"
class ChildA(Base):
def __init__(self):
Base.__init__(self)
class ChildB(Base):
def __init__(self):
super(ChildB, self).__init__()
ChildA()
ChildB()
主要区别在于ChildA__init__将无条件调用Base__init__而ChildB__init__将在任何类中调用__init__,该类恰好是自己祖先行中的ChildB祖先(这可能与您的预期不同)。
如果添加使用多重继承的ClassC:
class Mixin(Base):
def __init__(self):
print "Mixin stuff"
super(Mixin, self).__init__()
class ChildC(ChildB, Mixin): # Mixin is now between ChildB and Base
pass
ChildC()
help(ChildC) # shows that the Method Resolution Order is ChildC->ChildB->Mixin->Base
则Base不再是ChildB for ChildC实例的父级。现在super(ChildB,self)将指向Mixin,如果self是ChildC实例。
您已在ChildB和Base之间插入Mixin。你可以利用super()
因此,如果您设计的类可以在合作多重继承场景中使用,那么使用super是因为您不知道谁将在运行时成为祖先。
超级考虑的超级帖子和pycon 2015附带的视频很好地解释了这一点。
主要区别在于ChildA__init__将无条件调用Base__init__而ChildB__init__将在任何类中调用__init__,该类恰好是自己祖先行中的ChildB祖先(这可能与您的预期不同)。
如果添加使用多重继承的ClassC:
class Mixin(Base):
def __init__(self):
print "Mixin stuff"
super(Mixin, self).__init__()
class ChildC(ChildB, Mixin): # Mixin is now between ChildB and Base
pass
ChildC()
help(ChildC) # shows that the Method Resolution Order is ChildC->ChildB->Mixin->Base
则Base不再是ChildB for ChildC实例的父级。现在super(ChildB,self)将指向Mixin,如果self是ChildC实例。
您已在ChildB和Base之间插入Mixin。你可以利用super()
因此,如果您设计的类可以在合作多重继承场景中使用,那么使用super是因为您不知道谁将在运行时成为祖先。
超级考虑的超级帖子和pycon 2015附带的视频很好地解释了这一点。