help needed with classes/inheritance

Paul McGuire ptmcg at austin.rr.com
Wed Apr 23 12:41:27 EDT 2008


On Apr 23, 10:44 am, barbaros <barba... at ptmat.fc.ul.pt> wrote:
>
> If I understand correctly, in the above implementation I cannot
> define firstly a (non-oriented) body, and then build, on top of it,
> two bodies with opposite orientations. The point is, I want
> both oriented bodies to share the same base Body object.

What you are describing is composition+delegation, not inheritance,
and it would be the same answer in Java, C++, or OO-langue-du-jour.
Python makes delegation to the contained object easier than the others
(except maybe for OOldj) - no need to implement all the methods of the
contained object in the container, that just delegate the call to the
contained; use __getattr__ to get attributes of the contained object
that are not defined on the container (methods are attributes, too) as
shown below.  No inheritance in this example at all.

-- Paul


class BodyWithoutOrientation(object):
    def __init__(self,color):
        self.color = color
    def show_orientation(self):
        print "I don't lean one way or the other"

class OrientedBody(object):
    def __init__(self,base,orientation):
        self.base_body = base
        self.orientation = orientation
    def show_orientation(self):
        print "I lean to the " + \
            {
            OrientedBody.RIGHT : "right",
            OrientedBody.LEFT : "left",
            }[self.orientation],
        print "and my color is " + self.color
    # delegate any other attr lookups to the base_body object
    def __getattr__(self,attr):
        return getattr(self.base_body,attr)
OrientedBody.RIGHT = object()
OrientedBody.LEFT = object()

class LeftRightBody(object):
    def __init__(self,b):
        self.common_base = b
        self.left = OrientedBody(b,OrientedBody.LEFT)
        self.right = OrientedBody(b,OrientedBody.RIGHT)
    def show_orientation(self):
        print "I do both of these:"
        print "- ",
        self.left.show_orientation()
        print "- ",
        self.right.show_orientation()

base = BodyWithoutOrientation("purple")
lr = LeftRightBody(base)

base.show_orientation()
lr.show_orientation()

Prints:
I don't lean one way or the other
I do both of these:
-  I lean to the left and my color is purple
-  I lean to the right and my color is purple



More information about the Python-list mailing list