[Tutor] 'Right' way to implement mixins in Python?
chombee
chombee at nerdshack.com
Thu May 29 22:57:18 CEST 2008
On Wed, 2008-05-28 at 23:30 +0100, Alan Gauld wrote:
> > The lessons I learned are that, when implementing mixins using
> > multiple
> > inheritance:
> >
> > * Mixin classes should not derive from any base class (except
> > object)
> > * But they may assume that the classes they will be mixed in with do
> > derive from a certain base class, so they may assume the base class
> > is
> > there.
>
> Yes to both, regardless of language. As I said above you can make the
> mixins slightly more generally reusable by creating abstact mixins
> with explicit dependancy on an abstact interface. But better still is
> to
> avoid dependencies as much as possible where mixins are concerned.
> Instead build a protocol in the class framework outside the mixins
> and let them coerce the dependencies to suit the mixin interfaces.
Yeah I'd like to see how this dependency on an abstract interface is
implemented in Python also. The way I implemented my mixins, as I said,
the mixins did not inherit from anything but they assume that a certain
base class will be in the inheritance of any class they are mixed in to,
I just explained this in the module docstring. But it's less than ideal.
Even straight after writing that docstring, I started a new module and
started writing classes that used the mixins, and immediately forgot to
inherit from the base class that the mixins expect.
I suppose I could get the __init__ methods of the mixins to look for the
base class and complain if it's not there. What I tried to do in the
first place when the mixins themselves actually inherited their common
base class was better, because classes using the mixins didn't need to
remember to inherit that class themselves, but that ran into all sorts
of implementation problems as I've explained. Depending on an abstract
interface might be better but I'm not sure how it would work.
More information about the Tutor
mailing list