mixin class
Udo Gleich
udo.gleich at web.de
Tue Jul 29 04:03:51 EDT 2003
Hi,
> Why not simply
>
> class K1(object):
> pass
>
> class K2(object):
> pass
>
> mixed = type("K1_K2", (K1, K1), {})
> new_instance = mixed()
>
> print new_instance
>
almost.
If K1 has a constructor that takes arguments you get an
error when you call the constructor of the derived class
without an argument. Why do I want to do that? Usually
one would say that I should know the arguments of the
constructor of the derived class.
What I want to do is take *two objects*, derive from both
their classes, make a new object and combine the state of
the old objects.
I dont know if that is a good idea. I would appreciate comments
on the following solution. Especially the use of the dummy_init
function as an empty constructor looks not quite right to me.
---------------------------------------------------------------------
def dummy_init(self):
pass
class Mixin:
__shared_state = {"classes":{}}
def __init__(self):
self.__dict__ = self.__shared_state
def mix(self, original_instance, mixin_instance):
original_class = original_instance.__class__
mixin_class = mixin_instance.__class__
name = original_class.__name__ + '_' + mixin_class.__name__
mixed = self.classes.get(name,
type(name,
(mixin_class, original_class),
{"__init__": dummy_init}))
new_instance = mixed()
new_instance.__dict__.update(mixin_instance.__dict__)
new_instance.__dict__.update(original_instance.__dict__)
try:
new_instance.late_init_original()
except AttributeError:
pass
try:
new_instance.late_init_mixin()
except AttributeError:
pass
return new_instance
class K1(object):
def __init__(self, a):
self.a = a
class K2(object):
def late_init_mixin(self):
self.b = self.a + 1
mixer = Mixin()
new_instance = mixer.mix(K1(3), K2())
print new_instance
print new_instance.a, new_instance.b
-------------------------------------------------------------------------
More information about the Python-list
mailing list