Python multiple inheritance issues

Sorry, if this question was asked earlier, I could not find the answer while searching for other questions.

I am new to Python and am having multiple inheritance issues. Suppose I have 2 classes, B and C, that 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 

Now I want to define another class D that inherits from both B and C. D must inherit the implementation of B foo, but the C-implementation of the bar. How can I do it?

+5
source share
1 answer

Resisting the temptation to say “avoid this situation first,” one (not necessarily elegant) solution might 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 
+11
source

Source: https://habr.com/ru/post/1206525/


All Articles