2017-05-29 85 views
0

我有兩個類,一個從另一個繼承。我們稱它們爲ParentChild。 無論從這些類創建應使用功能funA,它看起來像下面Python - 繼承和方法覆蓋

funA(): 
    X = another_function() 
    Y = # some value 
    X.append(Y) 
    # do other computations 

兩個類,功能funA看起來幾乎相同的對象,除了功能another_function(),它以不同的方式計算列表XParentChild不同。當然,我知道我可以覆蓋Child類中的函數funA,但由於此函數非常長並且執行了多個操作,因此複製粘貼它會有點浪費。另一方面 - 我必須區分Parent類應使用another_function()的一個版本,Child類應使用another_function()的第二個版本。是否可能指向哪個版本的another_function(我們稱之爲another_function_v1another_function_v2)應該由每個類別使用或者唯一的解決方案是否覆蓋整個功能funA

+1

爲什麼不爲'function_calling_method'呼叫調用替換爲'another_function',那麼就重寫*中的孩子,*? – jonrsharpe

+0

是你的'funA'靜態或類/實例方法嗎? –

+0

@AzatIbrakov它是一種方法 – Ziva

回答

1

您的帖子不太清楚,但我認爲funAParent的一種方法。如果是的話,只需添加一些another_method方法調用正確的函數:

class Parent(object): 
    def another_method(self): 
     return another_function_v1() 

    def funA(self): 
     X = self.another_method() 
     Y = # some value 
     X.append(Y) 
     # do other computations 

class Child(Parent): 
    def another_method(self): 
     return another_method_v2() 

NB如果funA是一個類方法,你會希望another_method一類方法太...

1

我不知道你的another_functions來。我想他們是正常的功能,可以導入和使用

class Parent(object): 
    another_function = another_function_v1 
    def funA(self): 
     X = self.another_function() 
     Y = # some value 
     X.append(Y) 
     # do other computations 

class Child(Parent): 
    another_function = another_function_v2