5

Sorry if this question has been asked before, I could not find the answer while searching other questions.

I'm new to Python and I'm having issues with multiple inheritance. Suppose I have 2 classes, B and C, which inherit from the same class A, which are defined as follows:

class B(A):
    def foo():
        ...
        return

    def bar():
        ...
        return


class C(A):
    def foo():
        ...
        return

    def bar():
        ...
        return

I now want to define another class D, which inherits from both B and C. D should inherit B's implementation of foo, but C's implementation of bar. How do I go about doing this?

4
  • 1
    this is known as the diamond problem - mypythonnotes.wordpress.com/2008/11/01/… Commented Nov 9, 2014 at 22:50
  • it is better to explicitly say what do you want, in D.__init__ you can self.bar = C.bar Commented Nov 9, 2014 at 22:51
  • super().foo() in class D will call B.foo() once B is before C in the mro Commented Nov 9, 2014 at 23:19
  • @m.wasowski I think it would be better to do this directly in the class definition than to do it on an instance-by-instance basis at __init__ time. Commented Nov 9, 2014 at 23:26

1 Answer 1

11

Resisting the temptation to say "avoid this situation in the first place", one (not necessarily elegant) solution could be to wrap the methods explicitly:

class A: pass

class B( A ):
    def foo( self ): print( 'B.foo')
    def bar( self ): print( 'B.bar')

class C( A ):
    def foo( self ): print( 'C.foo')
    def bar( self ): print( 'C.bar')

class D( B, C ):
    def foo( self ): return B.foo( self )
    def bar( self ): return C.bar( self )

Alternatively you can make the method definitions explicit, without wrapping:

class D( B, C ):
    foo = B.foo
    bar = C.bar
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.