multiple inheritance super()

Michele Simionato michele.simionato at gmail.com
Sat Jul 30 05:35:29 EDT 2005


If I understand correcly you have a situation like this:

Base

 |

Parent1  Mixin
  |      |
  |      |
  Children1

Base

 |

Parent2  Mixin
  |      |
  |      |
  Children2


Base

 |

Parent3
  |
  |
  Children3

The Base class is pretty general, Parent1, Parent2 and Parent3 are more
specific, Children1 and Children2 requires the Mixin class, but
Children3 does
not require it.

Let me note that this looks like a sensible design and that I agree
that in simple
situations multiple inheritance could be the simplest solution.
Nevertheless 1)
I am scared of the case where you have hundreds of methods coming from
everywhere (ex. Zope) and 2) even in simple situations a solution
without
multiple inheritance is not that much worse.

Various solutions (using pseudocode):

1. use single inheritance and attach the mixin methods by hand:

   class Children2(Parent2): pass

   for methodname, method in methods_of(Mixin):
       setattr(Children2, methodname, method)

  if you think this is ugly, use a metaclass to attach the methods for
  you. This is probably still ugly, since it is akin to reimplementing
  multiple inheritance by hand. Still, it can be done, if you really
want.

2. use single inheritance and delegation. If "mixin" is a proxy to
   the methods in the mixin (for instance implemented as an attribute
   descriptor) you could do

   class Children2(Parent2):
         mixin = Proxy(Mixin)

   c2 = Children2()

   and then c2.mixin.method(args) would actually call Mixin.method(c2,
args).
   I like this solution since it is clear where methods come from and
it scales
   better to complex situations (still if you have only 2 or 3 methods
   multiple inheritance could be pretty fine).

3. think differently and use multimethods

  There are implementations of multimethods in Python (for instance in
PEAK).
  This example looks like a good candidate for a multiple dispatch
solution.
  You would use single inheritance and promote the mixin methods to
  multimethods. BTW, I think multimethods are pretty
  nifty and I would welcome them in standard Python.



              Michele Simionato




More information about the Python-list mailing list