2012-09-01 58 views
0

說,我有一些MainClass它在其方法的某個點上具有作爲MainClass屬性OtherClass的對象的實例化。在python中擴展類

mainobj = MainClass() 
isinstance(mainobj.otherclassobj, OtherClass) == True 

現在,我希望延長OtherClass,然後用MainClass有新的擴展類。

我是否有更方便的選擇,除了擴展MainClass並重新定義其所有方法self.otherclassobj實現它從ExtendedOtherClass

回答

1

如果您可以稍微更改MainClass的實施,則不需要繼承它。只要有默認使用OtherClass

class MainClass: 
    def __init__(self, ..., otherclass=OtherClass): 
     self.otherclassobj = otherclass() 
     ... 
    ... 

然後MainClass意志,但你可以通過ExtendedOtherClass作爲關鍵字參數。

2

如果您不需要OtherClass已經,你可以這樣做

from other_class_module import ExtendedOtherClass as OtherClass 

如果您需要這兩個類,或邏輯/方法改變 - 你需要重寫/擴展MainClass