lundi 8 janvier 2018

Load child class from base class

I have a base class BaseClass with multiple subclasses SubClass1, SubClass2. In practice the program only works with instances of one of the sub-classes. The sub-classes implement an interface with the save method. When loading a saved element, you do not know the class you are loading. Therefore I was considering having the load method in the base class, but this raised the question: how do I instantiate an element from one of the sub-classes in the base class ?

For clarity, here is some simple code:

class BaseClass:
    def load(self):
        #load element of subclass
        return subclass_element

class myInterface:
    __metaclass__ = ABCMeta
    @abstractmethod
    def save(self):
        raise NotImplementedError

class SubClass1(BaseClass, myInterface):
    def save(self):
        #save the element

class SubClass2(BaseClass, myInterface):
    def save(self):
        #save the element

I'm also open to any suggestions in favor of a different design. I'm not sure I'm not implementing an anti-pattern.

Aucun commentaire:

Enregistrer un commentaire