Multiple inheritance - How to call method_x in InheritedBaseB from method_x in InheritedBaseA?

Carl Banks pavlovevidence at gmail.com
Sun Sep 6 03:41:16 CEST 2009


On Sep 4, 3:01 am, The Music Guy <music... at alphaios.net> wrote:
> I have a peculiar problem that involves multiple inheritance and method calling.
>
> I have a bunch of classes, one of which is called MyMixin and doesn't
> inherit from anything. MyMixin expects that it will be inherited along
> with one of several other classes that each define certain
> functionality. It defines method_x, which it assumes will also be
> defined in the other class that MyMixin ends up getting inherited
> with. For example,
>
> class MyMixin(object):
>     def method_x(self, a, b, c):
>         ...
>
> class BaseA(object):
>     def method_x(self, a, b, c):
>         ...
>
> class BaseB(object):
>     def method_x(self, a, b, c):
>         ...
>
> class BaseC(object):
>     def method_x(self, a, b, c):
>         ...
>
> class FooX(MyMixin, BaseA):
>     ...
>
> class FooY(MyMxin, BaseB):
>     ...
>
> class FooZ(MyMixin, BaseC):
>     ...
>
> This all appears fine at first, but there is a problem: Each Foo's
> method_x must call the method_x of MyMixin as well as the method_x of
> each respective Foo's second base class. One cannot simply call
> FooN.method_x, because that will only call MyMixin.method_x and not
> that of the other base.
>
> One might be tempted to amend MyMixin's method_x so that it calls the
> parent's method_x before doing anything else:
>
> class MyMixin(object):
>     def method_x(self, a, b, c):
>         super(MyMixin, self).method_x(a, b, c)
>         ...
>
> ...but of course, that will fail with an AttributeError because
> MyMixin's only superclass is object, which does not have a method_x.

Out of curiosity, did you try this and are reporting that it resulted
in an AttributeError, or did you merely deduce that it would raise
AttributeError based on your knowledge of Python's inheritance?

I ask this rhetorically.  I know that you didn't try it (or that you
tried it and made a mistake) because if you had tried it (and not made
a mistake) you would have seen that it works exactly as you want it
to.


Carl Banks



More information about the Python-list mailing list