Two-level abstract class hierarchy without 'consistent method resolution' error

1.8k views Asked by At

I need two levels of abstract classes and a third level concrete class:

from abc import ABC

class Shape(ABC):
...

class Quad(ABC, Shape):
...

class Square(Quadrilateral)
...

This code generates TypeError: Cannot create a consistent method resolution against the declaration of Quad. I realize that the problem is a multiple inheritance ambiguity. Quad doesn't know whether to derive certain functions directly from ABC or from Shape, but how do I fix it? I can't drop ABC from Quad's declaration because then it won't be abstract anymore.

2

There are 2 answers

1
Keith Wiley On

Apparently, simply reversing the order of the parent classes to Quad fixes the problem. I'm still unclear on the underlying theory (although it can sort of be inferred), but at least my code is running now.

class Quad(Shape, ABC)
0
tcb On

This is explained in abc documentation:

Note that the type of ABC is still ABCMeta, therefore inheriting from ABC requires the usual precautions regarding metaclass usage, as multiple inheritance may lead to metaclass conflicts. There is also an example how to use ABCMeta directly.

With that your code would look like this:

from abc import ABC

class Shape(metaclass=ABCMeta):
...

class Quad(Shape, metaclass=ABCMeta):
...

class Square(Quadrilateral)
...

I don't know why it worked when ABC is the last class in the list, but the benefit of using ABCMeta is that you cannot put it at the beginning of the list.