Subclass dynamically

Gary Herron gherron at
Sat Aug 8 19:31:41 CEST 2009

Robert Dailey wrote:
> Hey,
> I have a class that I want to have a different base class depending on
> a parameter that I pass to its __init__method. For example
> (pseudocode):
> class MyDerived( self.base ):
>   def __init__( self, base ):
>     self.base = base
> Something like that... and then I would do this:
> foo = MyDerived( MyBase() )
> Note I'm using Python 3.1 on Windows. Thanks in advance.
Python makes it possible to change base classes, but that doesn't mean 
it ever a good idea.

Moreover, the assignment is at the class level, not the instance level:

    MyDerived.__bases__ = (base,) #A tuple of bases

would change the base class for the class MyDerived, and all instances 
past, present, or future.

Better (but still not good) might be a factory function that derives a 
class with the desired base class:

def Derive(base):
    class Derived(base):
    return Derived

DerivedClass = Derive(MyBase)
foo = DerivedClass(...)

I believe that will produce what you were looking for.

Gary Herron

More information about the Python-list mailing list