I have a class
class A(ABC):
@abstractmethod
def m():
pass
and a bunch of classes inheriting from it.
class M1(A):
...
class M2(A):
...
...
Some of these have a lot in common as they share a lot of functionality such that I would like to introduce a common base class which itself inherits from A
, but it does not introduce any new @abstractmethod
methods:
A
|
+----+----+
| | |
M1 M2 B
|
+--+--+
| |
K1 K2
What should the definition for class B
look like?
I'm on Python 3.8
EDIT: I am specifically asking as PyCharm tells me "B must inherit all abstract methods"
You can simply use
class B(A):
pass
or any other code that is common to all children, but without m
. This will still be abstract due to the absence of m
.
An alternative is to use
class B(A, ABC):
pass
In my opinion this is less good. This states that B
is both an A
and an ABC
, while the former alternative states that B
is an A
, and it is an ABC
insofar as much as A
is an ABC
itself.
Consider the case where you decide later on that A
is not an ABC
after all. For M1
and M2
, no change needs to be made. For B
, you now need to remove its being an ABC
as well. While making sure that A
and B
are synchronized in subclassing ABC
is not a huge overhead in terms of code maintenance, I think it does indicate that the design is problematic, PyCharm's warning about the former alternative notwithstanding (I would suppress it as a false-positive).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.