how to dynamically instantiate an object inheriting from several classes?

George Sakkis george.sakkis at gmail.com
Fri Nov 21 17:36:19 EST 2008


On Nov 21, 5:11 pm, Joe Strout <j... at strout.net> wrote:
> I have a function that takes a reference to a class, and then  
> instantiates that class (and then does several other things with the  
> new instance).  This is easy enough:
>
>     item = cls(self, **itemArgs)
>
> where "cls" is the class reference, and itemArgs is obviously a set of  
> keyword arguments for its __init__ method.
>
> But now I want to generalize this to handle a set of mix-in classes.  
> Normally you use mixins by creating a class that derives from two or  
> more other classes, and then instantiate that custom class.  But in my  
> situation, I don't know ahead of time which mixins might be used and  
> in what combination.  So I'd like to take a list of class references,  
> and instantiate an object that derives from all of them, dynamically.
>
> Is this possible?  If so, how?

Easily:

derived_cls = type('Derived', (cls1, cls2, *rest_classes), {})
item = derived_cls(**itemArgs)

You will probably want to cache the generated classes so that at most
one class is created for each combination of mixins.

HTH,
George



More information about the Python-list mailing list