2015-11-22 38 views
0

是否有可能像這樣合併兩個類的方法?Python類方法合併

class foo: 
    def __init__(self): 
     self.active = False 
    def doThing(self): 
     if not self.active: return 
     print("Just a foo here, boss") 

class bar(foo): 
    def __init__(self): 
     self.active = False 
    def doThing(self): 
     print("I shouldn't be showing unless I'm active!") 

f = foo() 
b = bar() 
f.doThing() 
b.doThing() 

這將輸出「我不應該顯示,除非我活躍!」當我希望它繼承父類的self.active檢查部分,從而使該方法在其餘部分運行之前返回。有沒有辦法做到這一點?

回答

3

您可以將檢查在一個單獨的函數:

class Foo: 
    def __init__(self): 
     self.active = False 

    def isActive(self): 
     return self.active 

    def doThing(self): 
     if not self.isActive(): return 
     print("Just a Foo here, boss") 

class Bar(Foo): 
    def __init__(self): 
     super().__init__() 

    def doThing(self): 
     if not self.isActive(): return 
     print("I shouldn't be showing unless I'm active!") 

或者備選:

class Foo: 
    def __init__(self): 
     self.active = False 

    def doThing(self): 
     if not self.active: return 
     return self.doPrint() 

    def doPrint(self): 
     print("Just a Foo here, boss") 

class Bar(Foo): 
    def __init__(self): 
     super().__init__() 

    def doPrint(self): 
     print("I shouldn't be showing unless I'm active!") 
+0

我喜歡這裏的選擇。您重構了代碼,以便OOP應用程序有意義。 OP做筆記,很多次,正確的代碼是邏輯上直觀的。錯誤的OOP代碼在邏輯上看起來不一致。類設計是OOP編程的關鍵。 –

0

其他的答案是正確的,合併功能,不作任何意義。雖然如果你想實現第二類並以OOP方式合併它,代碼如下。

class Bar(Foo): 
def __init__(self): 
    super().__init__() 

def doThing(self): 
    super(self).doThing() 
    if not self.isActive(): return 
    print("I shouldn't be showing unless I'm active!") 
+0

請注意,上述代碼是多餘的,檢查活動狀態是否完成兩次。這是一個糟糕的OOP設計的例子,它會產生冗餘代碼。 –