Multiple inheritance - How to call method_x in InheritedBaseB from method_x in InheritedBaseA?
The Music Guy
musicguy at alphaios.net
Wed Sep 9 01:27:09 EDT 2009
On Mon, Sep 7, 2009 at 3:30 PM, Carl Banks<pavlovevidence at gmail.com> wrote:
>
> That's not what you did in your original post, though.
>
> Mixins should be listed first among bases, which is how you did it in
> your original post, and how it had to be in order for it to "just
> work" as I claimed.
>
> class FooX(MyMixin, BaseA)
> class FooY(MyMixin, BaseB)
> class FooZ(MyMixin, BaseC)
>
>
>
> If you are concerned that a base class might not define method_x (and
> therefore that the super call from MyMixin would fail), then there are
> a couple things you can do. First thing is to consider whether you
> ought to be using two method instead of one.
>
> Otherwise the easiest thing is to catch and ignore AttributeError from
> MyMixin's method_x:
>
> class MyMixin(object):
> def method_x(self, a, b, c):
> try:
> f = super(MyMixin, self).method_x
> except AttributeError:
> pass
> else:
> f(a,b,c)
>
> Note that you don't want to call the super inside the try block
> otherwise you risk catching spurrious AttributeErrors.
>
> This strategy might hide some typo-style errors with the base class,
> so if you're worried about that, another strategy would be to define
> another mixin which provides an empty method_x:
>
> class ProvideMethodX(self):
> def method_x(self, a, b, c):
> pass
>
> Then if BaseB does not define method_x, derive FooY from it like this:
>
> class FooY(MyMixin,ProvideMethodX,BaseB)
>
> Finally (and probably least confusingly) you could use separate mixins
> for bases that define method_x and those that don't.
>
>
> Carl Banks
> --
> http://mail.python.org/mailman/listinfo/python-list
>
I was trying to adapt Ryles' code into my existing example. I did what
I thought Ryles did, but it didn't seem to work. I also tried flipping
the order of the parents, as you suggested, but that didn't seem to
change anything; it gives the same error.
Also, there is no fear that one of the bases will not define method_x.
The current API *requires* that all bases (MyMixin, BaseA, etc.)
define a method_x, so if it does not exist for a base class, the
developer isn't following the instructions. ;)
More information about the Python-list
mailing list