At Friday 10/11/2006 21:13, 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.

(Note that even using your design, B doesn't have to inherit from both A and AA, just inheriting from A is enough to be able to call AA.general_method)

It's hard to tell in this abstract terms, but maybe you should consider whether really B "is an" A, and A "is an" AA. Other kind of relationships are possible, like delegation ("behaves like") or the strategy pattern ("now behaves like...", at runtime).

For a more "concrete" example:

Ahhhh! I didn't notice this when I read your post.

Suppose all the animals in the world have only 1 or 2 legs.

I would not consider walk a method of Legs, but of Animal. An Animal "has" Legs; it may have OneLeg or TwoLegs. An Animal walks "using" its legs.

class Animal:
    def __init__(self, number_of_legs):
        # an animal has legs
        self.legs = CreateLegs(self, number_of_legs)

    def walk(self):
        # an animal uses its legs to walk
        self.legs.walk()

class Legs:
    def walk():
        raise NotImplementedError # an abstract Legs doesn't have how to walk

class OneLeg(Legs): # a monopod? like in Plinius? "http://en.wikipedia.org/wiki/Monopod_(creature)"
    def walk():
         # implement walking with one leg
         print "Look ma, just one leg!"

class TwoLegs(Legs):
    def walk():
         # implement walking with two legs
         print "Left, rigth, left, right..."

def CreateLegs(animal, number_of_legs):
    # legs might depend on animal too
    if number_of_legs==1: return OneLeg()
    elif number_of_legs==2: return TwoLegs()
    raise ValueError, "Invalid number of legs: %d" % number_of_legs

If walking in general, have some common structure, you can put the "sketch" on Legs and let the derived classes "fill the gaps". This is known as "Template Method Pattern" - look for it.


--
Gabriel Genellina
Softlab SRL
__________________________________________________
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis! ¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to