Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python multiple inheritance questions

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?

like image 387
user3462066 Avatar asked Nov 09 '14 22:11

user3462066


People also ask

What is multiple inheritance in Python with example?

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.

What is the problem with multiple inheritance in Python?

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.

How is multiple inheritance possible in Python?

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.


1 Answers

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
like image 131
jez Avatar answered Oct 16 '22 00:10

jez