13

Say I have

class A:
    # Some code

Then, I want to create an abstract subclass B of A, which itself is concrete. Should I use multi-inheritance for this purpose? If so, should I import ABC first, as in

class B(ABC, A):
    @abstractmethod
    def some_method():
        pass

, or should I import it last, as in

class B(A, ABC):
    @abstractmethod
    def some_method():
        pass
Shen Zhuoran
  • 385
  • 3
  • 13
  • 1
    Are you sure you want to do this in the first place? What is you use case? It is a bit strange to turn a concrete class abstract. – JohanL Sep 23 '18 at 06:10
  • 2
    Please add to the question what you are trying to achieve and what are the issues you encounter. Seems that possibly you need to do something different than what is asked. – Eduard Sep 23 '18 at 06:14
  • 5
    @JohanL In some frameworks, say in PyTorch (which is for deep learning), there are some generic classes designed to be inherited and modified to serve specific purposes for the user (say, to define a custom submodule of a neural network, you should inherit from `torch.nn.Module`). I might want to implement a group of concrete `Module`s, and extract an abstract base class to reduce duplication. That abstract class should still inherit from `Module`, which itself is concrete. – Shen Zhuoran Sep 24 '18 at 11:56

1 Answers1

12

Yes, multiple inheritance is one way to do this. The order of the parent classes doesn't matter, since ABC contains no methods or attributes. The sole "feature" of the ABC class is that its metaclass is ABCMeta, so class B(ABC, A): and class B(A, ABC): are equivalent.

Another option would be to directly set B's metaclass to ABCMeta like so:

class B(A, metaclass=ABCMeta):
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149