Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define an abstract method but require a subclass implementation

Tags:

python

Note I do not think that abc inherently solves what I'm looking for. Restating in another, maybe better way, I'm looking of a way to partially implement a Parent.method but require that there is a Subclass.method also, which uses and adds to the partial Parent.method implementation.

I would like to partially define an abstract class method, but still require that the method be also implemented in a subclass. For example:

class AbstractClass(object):
    def amethod():
        # some code that should always be executed here
        vars = dosomething()

        # But, since we're the "abstract" class
        # force implementation through subclassing
        if <somehow determine whether this has not been subclassed>:
            raise NotImplementedError

class ActualClass(AbstractClass):
    def amethod():
        # Actual class code
        code_here()

        # And execute the super class code.
        super(ActualClass, self).amethod()
like image 292
triccare Avatar asked Nov 27 '25 02:11

triccare


1 Answers

Note I do not think that abc inherently solves what I'm looking for.

Actually abc is exactly what you're looking for. Defining an implementation in the base class but decorating it as abstract requires deriving classes to redefine it. Of course this has the side effect of preventing you from instantiating the base class, which I assume is OK in your use case.

import abc


# inheritance from abc.ABC is important, as otherwise the decorators don't do anything
class AbstractClass(abc.ABC):
    @abc.abstractmethod
    def amethod(self):
        # some code that should always be executed here
        print("Base implementation")


class ActualClass(AbstractClass):
    # will return TypeError: Can't instantiate abstract class ActualClass with abstract methods amethod if not redefined
    def amethod(self):
        # Actual class code
        print("Actual implementation")

        # And execute the super class code. (only one super class so less confusing)
        super().amethod()


a = ActualClass()
a.amethod()
like image 159
LemonPi Avatar answered Nov 29 '25 16:11

LemonPi