2014-07-23 21 views
1

我有一個基於函數的代碼看起來像這樣:類視圖和「加薪NotImplementedError」

def foo(request): 
    raise NotImplementedError() 

這是怎麼認爲的基於類的視圖使用?

class FooView(View): 
    def get(self, request, *args, **kwargs): 
    raise NotImplementedError() 

編輯>問:問題是關於語法。 FooView不是一個抽象類,它是實現類。當我嘗試使用return raise NotImplementedError()時 - 它給了我一個錯誤。我應該把NotImplementedError放在get()還是其他一些功能?

+5

我不太確定你要在這裏做什麼。也許如果你能描述你正在尋找的_behavior_,我們可以更好地理解這個問題...... – mgilson

+0

這個想法是,FooView還沒有實現,但它必須被定義爲未來的發展。所以FooView必須是引發NotImplementedError()的空類,只是爲了方便。 – Oleg

+1

所以它應該是一個抽象的基類? – mgilson

回答

2

嘛,你這樣做正確,請撥打raise NotImplementedError()未實現的功能中,它會引起人們的關注每一個這些函數被調用時:

>>> class NotImplementedError(Exception): 
...  pass 
... 
>>> class FooView(object): 
...  def get(self): 
...   raise NotImplementedError() 
... 
>>> v = FooView() 
>>> v.get() 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<stdin>", line 3, in get 
__main__.NotImplementedError 

可以引發異常的任何地方,你認爲它是有用的,例如在構造函數中指示整個類沒有實現:

>>> class FooView(object): 
...  def __init__(self): 
...   raise NotImplementedError() 
... 
>>> v = FooView() 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<stdin>", line 3, in __init__ 
__main__.NotImplementedError 
+0

非常感謝!這是我正在尋找的。我沒有在網上找到這個。 – Oleg