mardi 19 octobre 2021

Python: automatically call all inherited classes [duplicate]

in my example I have a base class Processing, which handles all pre- and post processing. This class is meant to be inherited from, when an algorithm is implemented. After the implementation I would like to call all inherited instances and compare the results. What I would like to know: is there a way to automatically call all inherited instances without having to do so manually. Or even better: is there a way to detect all inherited classes, so that I do not need to do any "book-keeping" anywhere? To better explain my problem I have written a little example:

class BaseProcessing:
  def __init__(self, _data):
    self.data = _data

  def __call__(self):
    self.do_pre_processing()
    self.do_algorithm()
    self.do_post_processing()

  def do_pre_processing(self):
    """generic preprocessing steps"""
    print("Starting preprocessing")

  def do_algorithm(self):
    raise RuntimeError('Please inherit from this class and implement algorithm.')

  def do_post_processing(self):
    """generic post processing steps"""
    print("Starting post processing")

class SimpleAlgorithm(BaseProcessing):
  def do_algorithm(self):
    print("Simple calculations")


class SplineAlgorithm(BaseProcessing):
  def do_algorithm(self):
    print("Using splines for calculation")
...


if __name__ == "__main__":
    data = getData()

    # is there a way to automate the following code,
    # which automatically can detect all the inherited instances?
    simple = SimpleAlgorithm(data)
    simple()
    spline = SplineAlgorithm(data)
    spline()
    ...

Aucun commentaire:

Enregistrer un commentaire