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?
Inheritance is the mechanism to achieve the re-usability of code as one class(child class) can derive the properties of another class(parent class). It also provides transitivity ie. if class C inherits from P then all the sub-classes of C would also inherit from P.
The Problem with Multiple Inheritance If you allow multiple inheritance then you have to face the fact that you might inherit the same class more than once. In Python as all classes inherit from object, potentially multiple copies of object are inherited whenever multiple inheritance is used.
A class can be derived from more than one base class in Python, similar to C++. This is called multiple inheritance. In multiple inheritance, the features of all the base classes are inherited into the derived class. The syntax for multiple inheritance is similar to single inheritance.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With