[Tutor] 'Right' way to implement mixins in Python?
Alan Gauld
alan.gauld at btinternet.com
Fri May 30 01:40:15 CEST 2008
"Alan Gauld" <alan.gauld at btinternet.com> wrote > "Kent Johnson"
<kent37 at tds.net> wrote
>>> Mixins should be as independant...
>> I don't understand what you mean by this.
OK, I'll try to rephrase what I said last time. But its
gone midnight so it will be brief...
Basically all I meant was that rather than making the mixin inherit
from some specific problem-domain superclass it would be better
to extract out the dependency interface into a separate asbstract
class, C say, (ie one not intended to be instantiated) which can
be packaged with the mixins and therefore enhance reuse across
projects.
In the specific project using the mixins there is still a need to pass
in a project specific subclass (or in Python C-like) object which
can be done either by inheriting from C - which reverses the
dependency - or by simply using a C-like set of operations.
By moving the dependency from an ingheritance relationship
to a delegation rtelationship based on a parameterised class
(at the init level) we provide a mechanism whereby multiple
projects can reuse the mixin while putting the onus on sublassing
within the project rather than within the mixin. This works on the
theory that project specific code is much less likely to be generic
than mixin code.
So instead of
class MyMixin(ProjectSpecificSuperclass): pass
we move to
class C(object):
# define interface here
class MyMixin(object):
def __init__(self,c = C)
def someMethod(self):
#uses self.c here
Now using projects can either subclass C and pass that into
the Mixin constructor or just create C-like classes and pass
those in.
I hope thats at least slightly clearer! It wasn't intended to
be profound, it was just badly expressed!
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list