Python mixin with abstract methods overrides concrete methods

Viewed 261

Two mixin classes specify requirements as abstract methods. Together, the classes have a full set of concrete methods. However, they fail to combine into a concrete class: no matter which order I use to declare the concrete class, some abstract methods override the concrete ones.

Is there a way to prevent abstract methods from overriding the concrete methods? I believe this works in Scala for example.

What are alternative ways to specify the requirements?

Here is a concrete example:

import abc


class A(abc.ABC):
    @abc.abstractmethod
    def x(self):
        pass

    def y(self):
        return "A.y"


class B(abc.ABC):
    @abc.abstractmethod
    def y(self):
        pass

    def x(self):
        return f"B.x"


class AB(B, A):
    pass


class BA(A, B):
    pass


ab = AB()  # TypeError: Can't instantiate abstract class AB with abstract methods y

ba = BA()  # TypeError: Can't instantiate abstract class BA with abstract methods x
0 Answers
Related