簡體   English   中英

Python多重繼承,如果兩個基類都持有相同的方法,則調用第二個基類方法

[英]Python multiple inheritance, calling second base class method, if both base classes holding same method

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.**

Python多重繼承,如果兩個基類都持有相同的方法,則調用第二個基類方法

嘗試使用成分

+不惜一切代價避免多重繼承,因為它太復雜了以至於無法可靠。 如果您堅持使用它,那么就准備好了解類的層次結構,並花時間查找一切的來源。
+使用組合將代碼打包到模塊中,這些模塊可用於許多不相關的地方和情況。
+僅當有明確相關的可重用代碼段符合一個通用概念時,或者由於使用某種東西而必須這樣做時,才使用繼承。
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() 

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()

現在調用Derived().amethod()將打印DerivedBase1Base2 ,最后是CommonBase 訣竅是, super會將每個調用傳遞給self的MRO中的下一個類,即使該調用不在當前類的繼承層次結構中。 因此, Base1.amethod最終通過super調用Base2.amethod ,因為它們是在Derived實例上運行的。

如果您在通用基類中不需要任何行為,則只需pass其方法主體即可。 當然, Derived類可以繼承該方法,而無需編寫自己的版本並調用super來獲取其余方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM