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

ryles rylesny at gmail.com
Wed Sep 9 13:23:54 EDT 2009


On Sep 9, 1:47 am, The Music Guy <music... at alphaios.net> wrote:
> I should also mention--and I should have realized this much
> sooner--that each of the BaseN classes are themselves each going to
> have at least one common base which will define method_x, so each
> BaseN will be calling that if it defines its own method_x. Again,
> sorry I didn't mention that sooner. For some reason it didn't occur to
> me that it would be important. I feel dumb now... :P
>
> Here is the updated current example:
>
> class CommonBase(object):
>     def method_x(self, a, b c):
>         ... no call to superclass' method_x is needed here ...
>
> class MyMixin(object):
>    def method_x(self, a, b, c):
>        get_other_base(self).method_x(self, a, b, c)
>        ...
>
> class BaseA(CommonBase):
>    def method_x(self, a, b, c):
>        super(BaseA, self).method_x(a, b, c)
>        ...
>
> class BaseB(CommonBaset):
>    ...
>
> class BaseC(CommonBase):
>    def method_x(self, a, b, c):
>        super(BaseC, self).method_x(a, b, c)
>        ...
>
> class FooX(MyMixin, BaseA):
>    ...
>
> class FooY(MyMxin, BaseB):
>    ...
>
> class FooZ(MyMixin, BaseC):
>    ...

OK, how about this?

class CommonBase(object):
    def method_x(self, a, b, c):
        print "CommonBase"

class MyMixin(object):
   def method_x(self, a, b, c):
       print "MyMixin",
       super(MyMixin, self).method_x(a, b, c)

class BaseA(CommonBase):
   def method_x(self, a, b, c):
       print "BaseA",
       super(BaseA, self).method_x(a, b, c)

class BaseB(CommonBase):
   def method_x(self, a, b, c):
        print "BaseB",
        super(BaseB, self).method_x(a, b, c)

class BaseC(CommonBase):
   def method_x(self, a, b, c):
        print "BaseC",
        super(BaseC, self).method_x(a, b, c)

class FooX(MyMixin, BaseA):
    def method_x(self, a, b, c):
        print "FooX",
        super(FooX, self).method_x(a, b, c)

class FooY(MyMixin, BaseB):
    def method_x(self, a, b, c):
        print "FooY",
        super(FooY, self).method_x(a, b, c)

class FooZ(MyMixin, BaseC):
    # Supposing this class doesn't require a specialized method_x.
    pass


FooX().method_x(1, 2, 3)  # Prints 'FooX MyMixin BaseA CommonBase'
FooY().method_x(1, 2, 3)  # Prints 'FooY MyMixin BaseB CommonBase
FooZ().method_x(1, 2, 3)  # Prints 'MyMixin BaseC CommonBase'

---

Each method_x implementation uses super() to ensure that the next base
class method_x is called. The exception is CommonBase, which is
presumed to be the hierarchy root.

http://www.python.org/download/releases/2.2.3/descrintro/#cooperation
http://www.python.org/download/releases/2.3/mro



More information about the Python-list mailing list