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()
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With