python - 不应实例化的类

标签 python python-3.x class inheritance

我想创建一个类层次结构,其中我有一个类 Block,它可以自己实例化。然后我有一个 List 类,它继承自 Block 并包含所有列表共有的方法,最后我有类 OrderedListLableledList 等继承自 List。我希望人们能够实例化 OrderedList 等,但不能实例化 List

换句话说,您可以实例化一个普通的Block,也可以实例化一个OrderedList,它继承自List,而List 继承自 block ,但不能实例化List

谷歌的所有尝试都会导致抽象基类,但没有提供适合这种情况的示例,我无法推断。

最佳答案

下面与口译员的对话应该表明这是如何可能的。使用Block继承抽象基类后,只需将List上的初始化器标记为abstractmethod即可。这将防止类的实例化而不会对子类造成问题。

>>> import abc
>>> class Block(abc.ABC):
    def __init__(self, data):
        self.data = data


>>> class List(Block):
    @abc.abstractmethod
    def __init__(self, data, extra):
        super().__init__(data)
        self.extra = extra


>>> class OrderedList(List):
    def __init__(self, data, extra, final):
        super().__init__(data, extra)
        self.final = final


>>> instance = Block(None)
>>> instance = List(None, None)
Traceback (most recent call last):
  File "<pyshell#42>", line 1, in <module>
    instance = List(None, None)
TypeError: Can't instantiate abstract class List with abstract methods __init__
>>> instance = OrderedList(None, None, None)
>>> 

关于python - 不应实例化的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42837521/

相关文章:

python - 将 UnivariateSpline 与 SCIPY 结合使用

python-3.x - 对 Jupyter Notebook 单元的输出运行测试

python-3.x - keras中的三重损失,如何从合并向量中获取 anchor 、正向和负向

java - 快速询问 : function that prints array of cells - should it be inside my cell class definition?

java - 构建我的 Java Swing 应用程序。 IE。何时何地使用类和不使用类

python - 哪种方式将字典附加到列表更有效

python - 子类化时如何不必在 init 中键入 self

Python 正则表达式 findall

performance - Python列表追加和扩展 - 速度慢

r - 将数据框转换为 R 中的引用类对象