Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 888
Shen Zhuoran Avatar asked Sep 23 '18 06:09

Shen Zhuoran


1 Answers

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):
like image 79
Aran-Fey Avatar answered Oct 20 '22 01:10

Aran-Fey