mardi 9 avril 2019

Resolving class from a string through registry

Let's consider I have several modules:

SomeModules\
    module1.py
    module2.py
    module3.py
main_module.py

The main_module.py has two classes: Aggregator and AggregatorElement.

class Aggregator:
    _aggregator_element_list = None

    def __init__():
        _aggregator_element_list = list()

    def add_element(element):
        self._aggregator_element_list.add(element)

    def remove_element(idx):
        self._aggregator_element_list.remove(idx)


class AggregatorElement(ABC):
    name = None

    def __init__(name):
        self.name = name

    @abstractmethod
    def type():
        raise NotImplementedError

Now all of these module1, module2 and module3 provide some sort of specific implementation for the AggregatorElement class. Let's say they all implement the abstract method type() which returns a string representation.

Now I have a text file which contains a list of strings that match the strings that are returned by the type() method. I want the Aggregator class to load this text file and resolve the strings to their implementations from the appropriate modules (create objects and add them to the list)

What is the best way of accomplishing this? Am I approaching it correctly?

Aucun commentaire:

Enregistrer un commentaire