【问题标题】:Class based views and 'raise NotImplementedError'基于类的视图和“raise NotImplementedError”
【发布时间】:2014-07-23 15:43:45
【问题描述】:

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

def foo(request):
  raise NotImplementedError()

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

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

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

【问题讨论】:

  • 我不太确定你在这里做什么。也许如果您能描述您正在寻找的行为,我们就能更好地理解这个问题......
  • 这个想法是 FooView 还没有实现,但它必须为将来的开发定义。所以 FooView 必须是引发 NotImplementedError() 的空类,只是为了方便。
  • 所以应该是抽象基类吧?
  • 不,应该是实现类。编辑了问题本身,请检查它。我想我不够具体:)

标签: python django exception


【解决方案1】:

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

【讨论】:

  • 非常感谢!这就是我一直在寻找的。我没有在网上找到这个。
猜你喜欢
  • 2019-03-04
  • 2017-11-03
  • 1970-01-01
  • 1970-01-01
  • 2011-06-15
  • 1970-01-01
  • 2022-01-07
  • 2012-12-28
  • 2013-01-25
相关资源
最近更新 更多