Inheritance Question

Frank Millman frank at chagford.com
Sat Nov 11 01:31:52 EST 2006


Jackson wrote:
> I've got an inheritance question and was hoping brighter minds could
> guide me.  I am in the strange situation where some of the methods in a
> subclass are actually more general than methods in a superclass.  What
> is the preferred way to handle such situations.  My original thought was
> to do something like this:
>
> class AA(object):
> 	def general_method(): pass
>
> class A(AA):
>    # redefine general_method() to call a
>    # restricted version of AA.general_method()
>
> class B(A,AA):
>    # redefine general_method() to call AA.general_method()
>
> This seems ugly to me, and I am wondering if there is a better method.
> So any suggestions would be appreciated.
>

I don't have an answer, but I have a similar question, so I hope you
don't mind if I add it to this thread. Hopefully there will be some
commonality in the responses.

Continuing your analogy of animals, assume a class A with a 'walk'
method and an 'eat' method.

Most animals walk the same way, but a few don't, so I create a subclass
AW and override the walk method.

Most animals eat the same way, but a few don't, so I create a subclass
AE and override the eat method.

How do I create an instance of an animal that both walks and eats
differently?

This is how I do it at present.

class A(object):  # walks normally, eats normally
    def walk(self):
        normal walk
    def eat(self):
        normal eat

class AW(A):  # walks differently, eats normally
    def walk(self):
        different walk

class E(object):  # abstract class
    def eat(self):
        different eat

class AE(E,A):  #  walks normally, eats differently
    pass

class AWE(E,AW):  #  walks differently, eats differently
    pass

So I use multiple inheritance instead of subclassing to override the
eat method. It works, but it feels ugly. Is there a cleaner solution?

Thanks

Frank Millman




More information about the Python-list mailing list