[Python] In Python, how to enforce abstract method implementation in chain derived classes?

Discussão em 'Python' iniciado por Stack, Setembro 2, 2025.

  1. Stack

    Stack Membro Participativo

    In python, I can use ABC and abstractmethod to create an abstract class with some required methods:

    class Base(ABC):
    @abstractmethod
    def tester(self)->str:
    pass


    I create a derived class A that must implement the methods:

    class A(Base):
    def tester(self) -> str:
    return 'A'


    I now need another class B that derives from A, and inherits some other functions and attributes. However, I want to force B to implement its own version of those abstract methods. I have tried making B derive from Base as well:

    class B(A, Base):
    # method "tester" is not implemented.
    pass


    I want my linter to recognise that B does not implement that method and warn me about it. It doesn't do that. (I am using VSCODE with Pylance and Ruff.)

    a=A() # this is fine
    b=B() # this should warn me


    Is there some way to achieve this?

    Continue reading...

Compartilhe esta Página