Runtime mix-ins with new-style classes

Denis S. Otkidach ods at fep.ru
Mon Apr 8 11:24:33 EDT 2002


On 8 Apr 2002, Kevin Smith wrote:

KS> Before I started using the new-style classes (i.e. 'object'
KS> based), I was
KS> able to add mix-in base classes at runtime by modifying the
KS> __bases__
KS> attribute.  However, I recently tried to do the same thing
KS> with a new
KS> -style class and got an error telling me that __bases__ was
KS> a readonly
KS> attribute.  Is there a was to do runtime mix-ins with
KS> new-style classes?

1) You can automaticaly add mixins to all classes in module(s)
via new metaclasses approach (define global __metaclass__
variable before class definition is executed).

2) You can redefine variable that refer to class with new class
with mixin added:

module.MyClass = type(module.MyClass.__name__,
                      module.MyClass.__bases__+(MixIn,),
                      module.MyClass.__dict__)






More information about the Python-list mailing list