4

Can you please explain the following contradiction?

For this code:

class CL1(object):
    def __init__(self):
        super(CL1, self).__init__()
        print "class 1"


class CL2(object):
    def __init__(self):
        #super(CL2, self).__init__()
        print "class 2"


class CL3(CL2, CL1):
    def __init__(self):
        super(CL3, self).__init__()
        print "class 3"


instance = CL3()

the output is:

class 2

class 3

However, if I uncomment the line:

#super(CL2, self).__init__()

I get the output:

class 1

class 2

class 3

I don't understand why applying to the superclass of CL2 invokes the constructor of CL1. CL1 is not the constructor of CL2.

The link: How does multiple inheritance work with the super() and different __init__() arguments? doesn't explain why the line:

#super(CL2, self).__init__()

invokes the constructor of a class that is not the superclass of the class calling it.

Community
  • 1
  • 1
CrazySynthax
  • 13,662
  • 34
  • 99
  • 183
  • I use version 2.7 – CrazySynthax Nov 06 '16 at 17:59
  • 1
    To be specific, check this answer: http://stackoverflow.com/a/30187306/2063361 – Moinuddin Quadri Nov 06 '16 at 18:01
  • "depth-first left-to-right traversal" + "removing duplicates expect for the last" - thanks – CrazySynthax Nov 06 '16 at 18:07
  • 1
    Nice find, @anonymous! Does that answer your question CrazySynthax? If so, we can close this question as a duplicate of that one. It helps to bear in mind that the `super.__init__` calls all get passed the _instance_ that's currently being initialized, so when you do (eg) `super(CL3, self).__init__()` the `CL2.__init__` gets called with the new `CL3` instance as `self`, so the `CL3` MRO determines what happens next. – PM 2Ring Nov 06 '16 at 18:07
  • we can close it – CrazySynthax Nov 06 '16 at 18:12
  • 1
    Well, it's already closed as a duplicate, but I think the question anonymous found is better than the one chosen by Jean-François Fabre, which you've already said didn't help you. :) If you like, we can change the "dupe target" to anonymous's one. – PM 2Ring Nov 06 '16 at 18:15

0 Answers0