Regarding multiple parent inheritance, when I call the super
.__init__
, why doesn't parent2's __init__
function get called? Thanks.
class parent(object):
var1=1
var2=2
def __init__(self,x=1,y=2):
self.var1=x
self.var2=y
class parent2(object):
var4=11
var5=12
def __init__(self,x=3,y=4):
self.var4=x
self.var5=y
def parprint(self):
print self.var4
print self.var5
class child(parent, parent2):
var3=5
def __init__(self,x,y):
super(child, self).__init__(x,y)
childobject = child(9,10)
print childobject.var1
print childobject.var2
print childobject.var3
childobject.parprint()
Output is
9
10
5
11
12
If you want to use
super
inchild
to callparent.__init__
andparent2._init__
, then both parent__init__
s must also callsuper
:See "Python super method and calling alternatives" for more details on the sequence of calls to
__init__
caused by usingsuper
.You might be wondering, "Why use
Base
?". Ifparent
andparent2
had inherited directly fromobject
, thensuper(parent2,self).__init__(x,y)
would callobject.__init__(x,y)
. That raises aTypeError
sinceobject.__init__()
takes no parameters.To workaround this issue, you can make a class
Base
which accepts arguments to__init__
but does not pass them on toobject.__init__
. Withparent
andparent2
inheriting fromBase
, you avoid theTypeError
.Because
parent
is next in method resolution order (MRO), and it never usessuper()
to call intoparent2
.See this example:
This will output:
Python multiple inheritance is like a chain, in
Child
classmro
, thesuper
class ofParentA
isParentB
, so you need callsuper().__init__()
inParentA
to initParentB
.If you change
super().__init__('ParentA')
toBase.__init__(self, 'ParentA')
, this will break the inheritance chain, output:More info about MRO