Python多重继承问题

use*_*066 5 python inheritance multiple-inheritance

对不起,如果以前问过这个问题,我在搜索其他问题时找不到答案.

我是Python的新手,我遇到了多重继承的问题.假设我有两个类,B和C,它们继承自同一个类A,它们的定义如下:

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

    def bar():
        ...
        return


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

    def bar():
        ...
        return
Run Code Online (Sandbox Code Playgroud)

我现在想要定义另一个类D,它继承自B和C.D应该继承B的foo实现,但是C的实现吧.我该怎么做呢?

jez*_*jez 11

抵制诱惑说"首先避免这种情况",一个(不一定是优雅的)解决方案可能是明确地包装方法:

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 )
Run Code Online (Sandbox Code Playgroud)

或者,您可以使方法定义显式,而不包装:

class D( B, C ):
    foo = B.foo
    bar = C.bar
Run Code Online (Sandbox Code Playgroud)