I'm using Python 3.10. I have a parent class that has access to some diagnostic object, e.g. a timer:
from abc import ABC, abstractmethod
class Parent(ABC):
def __init__(self, timer):
self.t = timer
@abstractmethod
def run():
pass
I now have a bunch of child classes that implement run()
:
class Child1(Parent):
def run():
print("Foo")
class Child2(Parent):
def run():
print("Bar")
...
I want the above inheritance to, implicitly, be equivalent to
class Child1(Parent):
def run():
self.t.start()
print("Foo")
self.t.stop()
class Child2(Parent):
def run():
self.t.start()
print("Bar")
self.t.stop()
...
without me adding the start()
and stop()
calls explicitly. The act of inheriting run()
should be enough to surround all overriding implementations with suchlike calls -- a sort of "setup and teardown" that makes use of an object field. Is this possible?
Note that this isn't quite the same as this thread, where the solution is to raise an exception if the programmer doesn't manually add those calls into the implementation. That's almost the opposite of what I want: the calls should not be added.