1

i have a python script that contains the following classes and subclasses,

from abc import ABC, abstractmethod

class A(ABC):

    @abstractmethod
    def process(self):
        pass

class B(A):
    result= []
    def process(self):
        ...code...
        return result

class C(A):
    result= []
    def process(self):
        ...code...
        return result

class D(A):
    result= []
    def process(self):
        ...code...
        return result

so, each subclass of the abstract class A, does some process and appends the output to the 'result' list and then the 'process' function returns the result. I would like to know if there is a way to instantiate all subclasses and the function in these classes to be able to have access to return the results from the function for all subclasses in a list of lists.

I have looked at some answers in this post Python Instantiate All Classes Within a Module, but using the answers there I only get to substantiate the subclasses and do not know how to substantiate the 'process' function.

zara kolagar
  • 881
  • 3
  • 15
  • 2
    1. You don't want to have `result` as an attribute on the class. It's better to just let each call to `process()` return its result, and then collect the results from the function calling them. 2. Why not just instantiate all the classes and then call the `process()` function? How many classes do you have? If there are more than ten, you probably want to do it some other way. 3. Instantiating all the classes in the module would also try to instantiate `A`, but it's abstract, so that would fail. – Lennart Regebro Sep 24 '21 at 07:00
  • Thank you very much for your reply. I see your point and yes, I have many more subclasses in the file – zara kolagar Sep 24 '21 at 07:47
  • Then there is probably a better way than typing in tons of very similar subclasses, but that would be a different question. – Lennart Regebro Sep 24 '21 at 10:05

1 Answers1

2

The hard part was to find all the subclasses, because it uses the less known __subclasses__ special method. From that it is straightforward: instanciate an object for each subclass and call the process method on it:

final_result = []                      # prepare an empty list
for cls in A.__subclasses__():         # loop over the subclasses
    x = cls()                          # instanciate an object
    final_result.append(x.process())   # and append the result of the process method

But the Pythonic way would be to use a one line comprehension

final_result = [cls().process() for cls in A.__subclasses__()]
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252