mixin class

Michele Simionato mis6 at pitt.edu
Mon Jul 28 17:55:48 EDT 2003


Udo Gleich <udo.gleich at web.de> wrote in message news:<3F24F8D2.E1ADFB08 at web.de>...
> Hi,
> 
> I try to implement mixin classes. Thats why I
> need to make a new class at runtime.
> 
> --tmp.py-------------------------------------
> 
> import new
> 
> class K1(object):
>     pass
> 
> class K2(object):
>     pass
> 
> mixed =  new.classobj("K1_K2", (K1, K1), {})
> new_instance = new.instance(mixed, {})
> 
> print new_instance
> 
> ---------------------------------------------
> 
> Making a new instance from the new class works
> only if K1 is not derived from object. If I use
> new style classes I get the following traceback:
> 
> Traceback (most recent call last):
>   File "tmp.py", line 10, in ?
>     new_instance = new.instance(mixed, {})
> TypeError: instance() argument 1 must be class, not type
> 
> I use Python 2.2.3 and Win2000.
> 
> My question: How do I implement mixin classes
> with new style classes?
> 
> Thanks,
> 
> Udo

Why not simply
 
 class K1(object):
     pass
 
 class K2(object):
     pass
 
 mixed =  type("K1_K2", (K1, K1), {})
 new_instance = mixed()

 print new_instance
 
?

"type" is described in http://www.python.org/2.2.3/descrintro.html
(in one line very easy to miss ;)


      Michele




More information about the Python-list mailing list