help needed with classes/inheritance
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.
self.color = color
print "I don't lean one way or the other"
self.base_body = base
self.orientation = orientation
print "I lean to the " + \
OrientedBody.RIGHT : "right",
OrientedBody.LEFT : "left",
print "and my color is " + self.color
# delegate any other attr lookups to the base_body object
OrientedBody.RIGHT = object()
OrientedBody.LEFT = object()
self.common_base = b
self.left = OrientedBody(b,OrientedBody.LEFT)
self.right = OrientedBody(b,OrientedBody.RIGHT)
print "I do both of these:"
print "- ",
print "- ",
base = BodyWithoutOrientation("purple")
lr = LeftRightBody(base)
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