pythonpython-3.xclassinheritance

Class that should not be instantiated


I want to create a class hierarchy in which I have a class Block which can be instantiated by itself. Then I have a class List which inherits from Block and contains methods common to all lists, and finally I have classes OrderedList, LableledList etc that inherit from List. I want people to be able to instantiate OrderedList etc, but not List.

In other words, you can instantiate a plain Block and you can instantiate an OrderedList that inherits from List that inherits from Block, but you can't instantiate List.

All attempts to Google this lead to Abstract Base Classes, but none provides and example that fits this case and I am having trouble extrapolating.


Solution

  • The following conversation with the interpreter should show how this is possible. After inheriting from the Abstract Base Class with Block, you only need to mark the initializer on List as being an abstractmethod. This will prevent instantiation of the class without causing problems for child classes.

    >>> 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)
    >>>