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
2
  • 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. Commented Oct 5, 2016 at 13:17
  • That was useful @PM2Ring . Thank you Commented Oct 5, 2016 at 17:22

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes.That worked. But, my use-case is little different than just calling the constructor of the second class.Got it solved. Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.