Mixin class data

Paul Moore gustav at morpheus.demon.co.uk
Wed Oct 9 18:29:04 EDT 2002


I am trying to set up a class hierarchy, including a "normal" base
class, a user-supplied derived class, and some optional
mixins. Something like

class B:
    ...

class M1:
    ...

class M2:
    ...

class UserSupplied(B, M1, M2):
    pass

The real case is for a protocol handler, B does the donkey work of
picking the incoming command into tokens, then dispatching to methods
for each command. The mixins provide "standard" handlers for various
commands, and the user class provides the base methods that do the
work.

Now, in one of my mixins, I need to retain state. It's basically a
"current location" pointer.

So the question is basically, how do I set this up? I can use a
class-private variable, something like __ptr, to hold the data, but
how do I get it initialised? I'd rather not make it a requirement of
this particular mixin that the derived class call its __init__ routine
- after all, the derived class often won't *have* an __init__ and it's
the B.__init__ method that gets called - and B doesn't know about M1.

I have a suspicion that this needs the new-style class "cooperative
super call" machinery. But I'm not 100% certain, and I'm reluctant to
use it as (a) I'm not sure that there isn't a simpler way I'm missing,
and (b) I worry that I still might be requiring something from the
user supplied class (if it has an __init__ does it need to use super()
calls, or can it just blithely call B.__init__, never knowing anything
complicated is going on?) Basically, are cooperative super calls
something that only the lower levels of the hierarchy have to
participate in, or do the top levels need to know what's going on as
well?

I think I'd rather a simpler solution, but I'm not sure what it
is... Even testing for the attribute using hasattr() is annoying, as
I have to say hasattr(self, "__M2_pos") rather than just hasattr(self,
"__pos").

OK, I think I've made it clear that my thinking's muddled :-) Can
anyone help to offer a clearer and simpler solution?

Thanks,
Paul Moore



More information about the Python-list mailing list