2014-03-26 18 views
0

讓我們定義一個名爲Filter的類。我希望這個類能夠被子類擴展,我希望所有這些子類都可以覆蓋一個方法:job如何以pythonic方式重現Java界面行爲

更具體地說

class Filter(object): 
    def __init__(self, csvin=None): 
     self._input = csvin 

    # I want this to be abstract. All the classes that inherit from Filter should 
    # implement their own version of job. 
    def job(self): 
     pass 

一種說法,我想確保的Filter任何子類有一個名爲job方法。

我聽說過模塊abc,但我也讀到了這些概念,稱爲鴨子打字和EAFP。我的理解是,如果我是鴨子,我會試着跑

f = SomeFilter() 
f.job() 

看看它是否有效。這是我的問題,如果它提出任何異常,我應該更仔細,當我寫類SomeFilter

我很確定我不完全理解duck-typing和EAFP的含義,但是如果這意味着我不得不推遲調試(即在invokeation時間),那麼我不同意這個思維方式。我不明白爲什麼這麼多人似乎都很欣賞這種EAFP哲學,但我希望成爲他們的一部分。

有人能轉換我解釋一下如何在安全預測的方式實現這一目標,那就是通過防止程序員在一個Python的方式延伸Filter時犯了一個錯誤。

+0

你不能在編譯時強制此。但是,您可以在基類的job()中引發NotImplementedError來指示該方法在應該執行時沒有被覆蓋。 – arshajii

回答

1

您可以使用raise NotImplementedErroras per the documentation

class Filter(object): 
    def __init__(self, csvin=None): 
     self._input = csvin 

    # I want this to be abstract. All the classes that inherit from Filter should 
    # implement their own version of job. 
    def job(self): 
     raise NotImplementedError