Home > Mobile >  python: instaintiate all subclasses in a module along with their function output
python: instaintiate all subclasses in a module along with their function output

Time:09-24

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.

CodePudding user response:

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__()]
  • Related