我有一个基于函数的代码,如下所示:
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/