【发布时间】:2021-04-25 04:15:36
【问题描述】:
假设我有以下抽象类Foo:
import abc
class Foo(abc.ABC):
@abc.abstractmethod
def bar(self):
raise NotImplementedError
我应该在bar 方法的主体中添加什么?
我看到很多代码都有raise NotImplementedError,如上图所示。但是,这似乎是多余的,因为任何未实现 bar 的子类在实例化时都会引发 TypeError: Can't instantiate abstract class Foo with abstract methods bar。
把bar留空是不是Pythonic,如下:
import abc
class Foo(abc.ABC):
@abc.abstractmethod
def bar(self):
...
这是Abstract Base Classes 的 Python 文档中所做的,但我不确定这只是一个占位符还是如何编写代码的实际示例。
如果可以只留下三个点 (...) 的 bar,我应该什么时候使用 NotImplementedError?
【问题讨论】:
标签: python python-3.x abstract-class