不应该被实例化的类

5 python inheritance class python-3.x

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

换句话说,您可以实例化一个普通对象Block,也可以实例化一个继承自 的OrderedList对象,但您不能实例化。ListBlockList

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

Noc*_*wer 4

下面与口译员的对话应该表明这是如何可能的。从抽象基类继承后Block,只需将初始化器标记Listabstractmethod. 这将防止类的实例化,而不会导致子类出现问题。

>>> 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)
>>> 
Run Code Online (Sandbox Code Playgroud)