0

I'm trying to understand Method Resolution Order in multiple inheirtance. Here's the code that I'm using.When I try to create the object of class 'ClassC', only the constructor of ClassA is getting called.How is the methods resolved in this case?

class ClassA:
    def __init__(self):
        print "inside a's init"

class ClassB:
    def __init__(self):
        print "inside b's init"

class ClassC(ClassA,ClassB):
    pass

c = ClassC()

Output:

inside a's init
Heisenberg
  • 185
  • 3
  • 10
  • You should be using new-style classes in Python 2, eg `class ClassA(object):` (in Python 3, all classes are new-style). And then add `super(ClassA, self).__init__()` to the `.__init__` method of `ClassA`. (You can also add a similar call to `ClassB`, but it's not necessary because `ClassB` is the end of `ClassC`'s inheritance chain). If the answer by Python core dev Raymond Hettinger in the linked question doesn't fully answer your question, please let me know. – PM 2Ring Oct 05 '16 at 13:17
  • That was useful @PM2Ring . Thank you – Heisenberg Oct 05 '16 at 17:22

1 Answers1

0

There is a python PEP I believe that covers the MRO algorithm in detail but it's rather complex. Additionally, it's covered in the book Fluent Python. I believe the short story is that it goes from left to right

if you switch to

class ClassC(ClassB,ClassA):
    pass

I bet you would see a change. (update, you will definitely see a change)

Also if you call

help(c)

you should see the mro printed out.

bravosierra99
  • 1,331
  • 11
  • 23
  • Yes.That worked. But, my use-case is little different than just calling the constructor of the second class.Got it solved. Thank you! – Heisenberg Oct 05 '16 at 17:24