-3

Is it possible to subclass dynamically? I know there's ____bases____ but I don't want to effect all instances of the class. I want the object cf to polymorph into a mixin of the DrvCrystalfontz class. Further into the hierarchy is a subclass of gobject that needs to be available at this level for connecting signals, and the solution below isn't sufficient.

class DrvCrystalfontz:
    def __init__(self, model, visitor, obj=None, config=None):
        if model not in Models.keys():
            error("Unknown Crystalfontz model %s" % model)
            return
        self.model = Models[model]
        if self.model.protocol == 1:
            cf = Protocol1(self, visitor, obj, config)
        elif self.model.protocol == 2:
            cf = Protocol2(self, visitor, obj, config)
        elif self.model.protocol == 3:
            cf = Protocol3(self, visitor, obj, config)
        for key in cf.__dict__.keys():
            self.__dict__[key] = cf.__dict__[key]
makes
  • 6,438
  • 3
  • 40
  • 58
Scott
  • 5,135
  • 12
  • 57
  • 74
  • Can you explain your use case a little more, and why the above solution doesn't work? – Jason Pratt Jun 19 '09 at 20:58
  • 4
    Please restore the original question, this is now completely useless to anybody who hasn't seen it. If you have an answer to your own question then create an _answer_! – nikow Jun 19 '09 at 22:57

1 Answers1

2

I'm not sure I'm clear on your desired use here, but it is possible to subclass dynamically. You can use the type object to dynamically construct a class given a name, tuple of base classes and dict of methods / class attributes, eg:

>>> MySub = type("MySub", (DrvCrystalfontz, some_other_class), 
         {'some_extra method' : lamba self: do_something() })

MySub is now a subclass of DrvCrystalfontz andsome_other_class, inherits their methods, and adds a new one ("some_extra_method").

Brian
  • 116,865
  • 28
  • 107
  • 112