Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python多重继承问题_Python_Inheritance_Multiple Inheritance - Fatal编程技术网

Python多重继承问题

Python多重继承问题,python,inheritance,multiple-inheritance,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

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

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

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

    def bar():
        ...
        return


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

    def bar():
        ...
        return

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

为了抵制说“首先要避免这种情况”的诱惑,一个(不一定是优雅的)解决方案可以是显式地包装这些方法:

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 )
或者,您可以使方法定义显式,而无需换行:

class D( B, C ):
    foo = B.foo
    bar = C.bar

这就是所谓的钻石问题——最好在
D中明确地说出你想要什么。你可以
self.bar=C.bar
super().foo()
在类D中调用
B.foo()
一次
B
在中的
C
之前mro@m.wasowski我认为直接在类定义中执行此操作比在
\uuuuu init\uuuu
时逐个实例执行要好。