Reputation: 53
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?
Upvotes: 5
Views: 821
Reputation: 15349
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
Upvotes: 11