vendredi 29 juin 2018

How to get all subclasses of an abstract base class in Python

Let's say you have an abstract base class with multiple subclasses as follows:

from abc import ABC, abstractmethod

class Parent(ABC):
    @abstractmethod
    def important_func(self):
        pass

class Child1(Parent):
    def important_func(self):
        # Define implementation here
        return

class Child2(Parent):
    def important_func(self):
        # Define implementation here
        return

What I would like to be able to do is either add a static method to Parent or just add a function in the module that will allow me to access all of Parent's subclasses with either an iterator or by returning a container of them.

Something like:

instantiated_subclass_list = [cls() for cls in Parent.__subclasses__()]

This method of finding subclasses looked promising:

How to find all the subclasses of a class given its name?

however, I am not sure if the case still holds when the parent class is an abstract base class and since there isn't any detail on the __subclasses__ method in the docs I feel like there is probably a better (possibly more "pythonic") way to accomplish this.





Aucun commentaire:

Enregistrer un commentaire