基于类的视图与'抛出未实现错误

1 投票
1 回答
3194 浏览
提问于 2025-04-18 14:28

我有一段基于函数的代码,长得像这样:

def foo(request):
  raise NotImplementedError()

那么在基于类的视图中应该怎么用呢?

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

编辑 > 问题:这个问题是关于语法的。FooView 不是一个抽象类,它是一个具体实现的类。当我尝试使用 return raise NotImplementedError() 时,出现了错误。我应该把 NotImplementedError 放在 get() 里面,还是放在其他函数里呢?

1 个回答

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

撰写回答