1

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.

Mew
  • 368
  • 1
  • 11
  • I would suggest that a better pattern to look at would be a proxy which does the timing rather than having the super class hold the timer. – quamrana Nov 23 '22 at 18:48
  • 1
    Does this answer your question? [python parent class 'wrapping' child-class methods](https://stackoverflow.com/questions/2065112/python-parent-class-wrapping-child-class-methods) or [Python Wrap Class Method](https://stackoverflow.com/questions/6780907/python-wrap-class-method) – Dash Nov 23 '22 at 19:00
  • This is not how inheritance works. One way you *could* set this up is to simply have the `Parent` class define `run` to call *another* method which is the one that is overriden in the subclasses – juanpa.arrivillaga Nov 23 '22 at 19:05
  • Does the accepted answer to this [question](https://stackoverflow.com/questions/46052736/python-proxy-class) help at all? – quamrana Nov 23 '22 at 19:51

0 Answers0