Python多重继承,调用第二个基类方法,如果两个基类都持有相同的方法

Siv*_*ddy 2 python class

class A:
    def amethod(self): print("Base1")


class B():
    def amethod(self): print("Base3")

class Derived(A,B):
    pass

instance = Derived()
instance.amethod() 
#Now i want to call B method amethod().. please let me know the way.**
Run Code Online (Sandbox Code Playgroud)

Python多重继承,调用第二个基类方法,如果两个基类都持有相同的方法

gal*_*yan 5

尝试使用组合

+不惜一切代价避免多重继承,因为它太复杂而不可靠。如果您坚持使用它,那么准备好了解类层次结构并花时间查找所有内容的来源。
+使用组合将代码打包成模块,用于许多不同的不相关的地方和情况。
+仅当有明确相关的可重用代码段适合单个通用概念时,或者由于您正在使用的某些东西而必须这样做时,才使用继承。
class A:
    def amethod(self): print("Base1")


class B:
    def amethod(self): print("Base3")

class Derived2:
    def __init__(self):
        self.a = A()
        self.b = B()

    def amthodBase1(self):
        self.a.amethod()

    def amthodBase3(self):
        self.b.amethod()

instance2 = Derived2()
instance2.amthodBase1() 
instance2.amthodBase3() 
Run Code Online (Sandbox Code Playgroud)


Blc*_*ght 5

Galaxyan 的答案表明组合可能是最好的答案。多重继承的设计和调试通常很复杂,除非您知道自己在做什么,否则很难做到正确。但如果您确实想要它,这里有一个答案,解释如何使其发挥作用:

为了使多重继承正常工作,基类通常需要与其子类合作。Python 的super函数使得设置起来并不太困难。您通常需要继承中涉及的类的公共基础(以停止继承链):

class CommonBase:
    def amethod(self):
        print("CommonBase")
        # don't call `super` here, we're the end of the inheritance chain

class Base1(CommonBase):
    def amethod(self):
        print("Base1")
        super().amethod()

class Base2(CommonBase):
    def amethod(self):
        print("Base2")
        super().amethod()

class Derived(Base1, Base2):
    def amethod(self):
        print("Derived")
        super().amethod()
Run Code Online (Sandbox Code Playgroud)

现在调用Derived().amethod()将打印Derived, Base1, Base2, 最后CommonBase。技巧在于super将每个调用传递给 MRO 中的下一个类self,即使它不是当前类的继承层次结构中的下一个类。因此Base1.amethod最终调用Base2.amethodviasuper因为它们是在 的实例上运行的Derived

如果您不需要公共基类中的任何行为,则其方法体只需为pass. 当然,Derived类可以只继承该方法,而无需编写自己的版本并调用super以获取其余部分。