我正在尋找關於如何構建一些項目的建議,我將繼續努力。python中的組成繼承
我得到一個基類,有一些方法。
class Base(object):
def method1(self):
# some code
def method2(self):
# some code
def method3(self):
# some code
... and some other methods
對於我的項目,我無法修改基類,爲了應用我的項目需求,我必須修改基類。
我有幾個要求,可能會啓用或不。取決於給定的配置。即我希望能夠重寫method1(),method2(),method3()或它們的任意組合。
一種替代方法是構造幾個繼承類。
class Child1(Base):
def method1(self):
# some code
class Child2(Base):
def method2(self):
# some code
class Child3(Base):
def method3(self):
# some code
然後可能使用多重繼承來應用它們的任何組合。然而,這種方法不能很好地覆蓋所有可能的組合。(例如,如果我將有Child4(),會發生什麼?)
另一種方法是隻有一個繼承類並使用if
子句來選擇是否調用超級方法或應用派生行爲。
class Child(Base):
def method1(self):
if not self.override1:
# call super
else:
# some code
def method2(self):
if not self.override2:
# call super
else:
# some code
def method3(self):
if not self.override3:
# call super
else:
# some code
我比較贊成這種替代,但是我覺得有必須是這樣做的更好的面向對象方法。
任何想法或建議?
非常感謝
PS:我不得不Python 2.7版,因爲我打算共享的代碼,我寧願有一個解決方案,易於平均Python程序員瞭解(而不是隻能由高級程序員)。
問題可能是過於寬泛。如果修改的程度導致實例的行爲與沒有修改的實例的行爲顯着不同 - 直到它可以被認爲是不同的事情(儘管是相關的),那麼我會說你最後的解決方案是不正確的,你可能需要多重繼承/混搭方法。 – wwii