python - 基于类的 View 和 'raise NotImplementedError'

标签 python django exception

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

def foo(request):
  raise NotImplementedError()

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

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

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

最佳答案

好吧,你做得正确,在未实现的函数内调用 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

关于python - 基于类的 View 和 'raise NotImplementedError',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24915059/

相关文章:

c++ - 捕获异常后确定异常类型?

android - 对话框使我的应用程序崩溃

html - 为什么在 django 中使用 xhtml2pdf 呈现为 pdf 时,html 表中的某些列会崩溃?

Python手动定义matplotlib xlim()

python - scikit : Wrong prediction for this case

python - pandas 数据框中每天每个类别的运行总计

python - 无法在 Django 测试中模拟模型的方法

django - Django 模板系统中的 bool 逻辑

c# - 如何在一个 catch block 中捕获所有类型的异常?

python - 调用 super() 时,元类如何与 MRO 列表一起工作?