mardi 21 novembre 2017

parameterizing a python object with a generic factory

I am trying to parametrize my objects with a json string provided at runtime through a rest API. I have come up with the following design. It works, but I feel like using class reflection and setattr are bad programming practices...but I don't know any other way of doing this in the fully generic way I want (I would like to be able to extend classes in the future which have new attributes, register more nested classes, etc)

Is this JUST awful, is there a better way?

class Factory:
    contains = {}

    @staticmethod
    def subclass(this, args):
        klass = next((cls for cls in this.__class__.__subclasses__(this) if cls.__name__ == args.get('type', None)),
                            this.__class__)
        return klass()

    def __init__(self, d=None):
        for key, value in self.contains.items():
            args = d.get(key, None)
            child = self.subclass(value, args)
            setattr(self, key, child)

class Clock(Factory):
    def tick(self):
        print("base clock tick")

class DigitalClock(Clock):
    def tick(self):
        print("digital clock tick")

class House(Factory):
    contains = {'clock': Clock}
    def __init__(self, d):
        self.color = d.get('color','red')
        super().__init__(d)


H = House({'clock': {'type': "DigitalClock"}, 'color': 'blue'})
H.clock.tick()

Aucun commentaire:

Enregistrer un commentaire