gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 05:06:28 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com