1

I just have one small question about initialization. In Python, and when we do a Multiply inherit, what's the difference between call the super function of child class and call each of them separate?

classA(B,C)

super(A,self).__init__()

#---and---#

B.__init__(self)
C.__init__(self)

Thanks

illunara
  • 327
  • 1
  • 5
  • 15
  • Did you mean to place `super()` *inside* of `A`'s `__init__()` method? Please fix your code, this code will generate the (obvious) IndentationError, as well as a NameError for `classA`. – Joel Cornett Feb 25 '13 at 15:04
  • Oh i'm sorry. I just wrote it for short :D – illunara Feb 25 '13 at 15:16

1 Answers1

1

The main difference is that if classes B and C have a common ancestor, with the super() call, that ancestor's __init__() will only be called once. By calling the parents' __init__() method explicitly as in your example, the common ancestor's __init__() will end up being called twice.

You can read about how super() accomplishes this from Guido's explanation.

Below is a demonstration of the explicit call to the parents' __init__() and how it calls the common ancestor twice:

>>> class A(object):
...   def __init__(self):
...     print "A"
... 
>>> class B(A):
...   def __init__(self):
...     A.__init__(self)
...     print "B"
... 
>>> class C(A):
...   def __init__(self):
...     A.__init__(self)
...     print "C"
... 
>>> class D(B,C):
...   def __init__(self):
...     B.__init__(self)
...     C.__init__(self)
...     print "D"
... 
>>> D()
A
B
A
C
D
<__main__.D object at 0x106de1d10>
>>> 

And this is what happens with super()

>>> class A(object):
...   def __init__(self):
...     print "A"
... 
>>> class B(A):
...   def __init__(self):
...     super(B,self).__init__()
...     print "B"
... 
>>> class C(A):
...   def __init__(self):
...     super(C,self).__init__()
...     print "C"
... 
>>> class D(B,C):
...   def __init__(self):
...     super(D,self).__init__()
...     print "D"
... 
>>> D()
A
C
B
D
<__main__.D object at 0x10d34ec90>
>>> 
entropy
  • 3,134
  • 20
  • 20