Shen Zhuoran
Shen Zhuoran

Reputation: 414

How to create an abstract subclass of a concrete superclass in Python 3?

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

Upvotes: 15

Views: 2819

Answers (1)

Aran-Fey
Aran-Fey

Reputation: 43126

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

Upvotes: 13

Related Questions