mixin class

Jeremy Bowers jerf at jerf.org
Thu Jul 31 05:42:50 CEST 2003


On Mon, 28 Jul 2003 12:20:02 +0200, Udo Gleich wrote:
> My question: How do I implement mixin classes
> with new style classes?

Um, if I understand what you're trying to do correctly, it's easy:

--------------
import random

class A(object): pass
class B(object): pass
class C(object): pass
class D(object): pass

mixin = random.choice([C, D])

class A_B_and_C_or_D(A, B, mixin): pass

newName = A_B_and_C_or_D

newInstance = newName()
----------------

(Warning: Didn't actually type this in)

The classes being derived from can be variable; in fact I do this rather
too frequently for my own good, perhaps. (I tend to use it for class I
want to be intimately involved with each other, but also usable
separately, having one of them dynamically derive from either object or
the other class, depending on whether the other class is available.) 

So in this example, on any given run, class A_B_and_C_or_D will always
derive from A and B, and may derive from either of C or D. 

You can dynamically do this in a loop or something if you're feeling
creative, if you assign the class to new names, as I did here for
"newName". AFAIK there's no way to programmatically create new classes
with generated names without resorting to eval (bad idea), but you can
bind them to new names after creation and that works OK.

----------------

classesILike = {}
for i in range(10):
    class tmp(object): pass
    classesILIke[i] = tmp

----------------

and of course "tmp" may derive from what it will.

The inheritance list is as dynamic as anything else in Python; feel free
to use it that way. Personally I find this is a "killer feature"... you'd
find it hard to describe in advance when you'd want it, but when
you want it, you want it ***badly***, because the kludge will be a
killer... and there are very, very few languages that can do this cleanly
(and still share Python's other benefits).




More information about the Python-list mailing list