![](/img/trans.png)
[英]Python multiple inheritance is not showing class variables or method of second inherited base class
[英]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()
將打印Derived
, Base1
, Base2
,最后是CommonBase
。 訣竅是, super
會將每個調用傳遞給self
的MRO中的下一個類,即使該調用不在當前類的繼承層次結構中。 因此, Base1.amethod
最終通過super
調用Base2.amethod
,因為它們是在Derived
實例上運行的。
如果您在通用基類中不需要任何行為,則只需pass
其方法主體即可。 當然, Derived
類可以繼承該方法,而無需編寫自己的版本並調用super
來獲取其余方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.