2016-11-29 60 views
2

我有兩個類共享很多常見的東西,除了一個功能f(x)python類繼承代碼重用

class A(object): 
    def __init__(self): 
     // some stuff 
    def g(self): 
     // some other stuff 
    def f(self, x): 
     // many lines of computations 
     q = ... 
     y = ... 
     return y 

class B(A): 
    def f(self, x): 
     // same many lines as in A 
     q = ... 
     y = ... 
     // a few extra lines 
     z = ... # z needs both y and q 
     return z 

在這種情況下,我必須在B類中從頭開始定義f(x)嗎?是否有一些技巧重新使用A.f(x)中的代碼?我能想到的

一種方法是使q實例屬性self.q,然後執行以下操作

def f(self.x): 
    y = A.f(self, x) 
    // a few extra lines 
    z = ... # using y and self.q 
    return z 

或許讓A.f(x)回報都qy,然後調用A.f(self, x)在B的的f(x)定義。

這些方法是否是標準方法?有更好的東西嗎?

+0

'self.q'將是一個實例屬性。 –

+0

已更正。謝謝。 – nos

+0

似乎是對我有效的方法。雖然'B'沒有繼承'g'函數,但它有關係嗎? –

回答

0

讓我們假設你想圍繞類組織你的代碼。如果是這樣的話,那麼我會強烈建議使用super引用父類:

class MyA(object): 
    def f(self, x): 
     print 'MyA' 
     return x 


class MyB(MyA): 
    def f(self, x): 
     print 'MyB' 
     print super(MyB, self).f(x) 

這種方法可以讓你堅持使用類和引用是繼承類的慣用方式。

如果你不需要用這種方式來組織你的代碼,或者有其他理由把事情分解成你的代碼中不關心這些類的其他部分可用的函數,那麼你可以移動你的f邏輯轉換成函數。

下面是一個例子:

def f(x): 
    return x 


class MyA(object): 
    def f(self, x): 
     return f(x) 


class MyB(MyA): 
    def f(self, x): 
     y = f(x) 
     ... 
     return y