Question

I am having some problem using multiple inheritance in Python and can't understand what I am doing wrong.

I have three classes A,B,C defined as follows it does not work.

class A(object):
   def __init__(**kwargs):
     .
     .

class B(object):
   def __init__(**kwargs):
    # prepare a dictionary "options" with the options used to call A
    super(B,self).__init__(**options)

   def coolmethod(x):
      #some cool stuff

For A and B I don't have any problems.

I want to create a third class C that inherits both from A and B so that I can the coolmethod defined in B, but would like to use the constructor defined in A.

Trying to define class C(A,B) does not work because the MRO is not defined.

But defining class C(B,A) does not allow me to use A.init rather than B.init.

How can I solve the issue?

Was it helpful?

Solution

You can call A.__init__() directly instead of using super() in C:

class C(B,A):
    def __init__(self, **kwargs):
        A.__init__(self, **kwargs)

OTHER TIPS

You can use

class A(object):
    def __init__(self, **kwargs):
        super(A, self).__init__(**kwargs)

if you expect multiple inheritance from A and something else. This way, A.__init__ will always be called.

The order is important because of the way method resolution works in python. If you have C inherit from (A, B), it means that if you invoke a method on C that exists both on A and B, the one on A is selected (it has precedence). If you write super(A, self).method in class A, it means you want to extend functionality provided by method. Therefore, it would be strange to skip over one such extension if both A and B had such extensions and C inherited from both. That's why when you call C.method, it will execute A.method, which will call B.method when it invokes super(A, self).method. In other terms, it's as if A inherited from B for the purpose of method extension. This is different when C inherits from (B, A).

Note that __init__'s first argument should always be self, just like for every method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top