Python – Subclassing in Python

pythonsubclassing

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]

Best Solution

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").