16

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
3
  • 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. Commented Sep 23, 2018 at 6: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. Commented Sep 23, 2018 at 6: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 Modules, and extract an abstract base class to reduce duplication. That abstract class should still inherit from Module, which itself is concrete. Commented Sep 24, 2018 at 11:56

1 Answer 1

13

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):
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.