基于类的视图和'引发NotImplementedError'

时间:2014-07-23 15:43:46

标签: python django exception

我有一个基于函数的代码,如下所示:

def foo(request):
  raise NotImplementedError()

这应该如何在基于类的视图中使用?

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

编辑>问题:问题是关于语法的。 FooView不是一个抽象类,它是实现类的。当我尝试使用return raise NotImplementedError()时 - 它给了我一个错误。我应该将NotImplementedError放在get()或其他功能中吗?

1 个答案:

答案 0 :(得分: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