barbaros a écrit :
On Apr 23, 10:48 am, Bruno Desthuilliers <bruno.
[EMAIL PROTECTED]> wrote:

My question is: can it be done using inheritance ?
Technically, yes:

class OrientedBody(Body):
   def __init__(self, orient=1):
     Body.__init__(self)
     self.orient = 1

Now if it's the right thing to do is another question...

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.

Then it's not a job for inheritence, but for composition/delegation - Sorry but I didn't get your specs quite right :-/

Now the good news is that Python makes composition/delegation close to a no-brainer:

class Body(object):
   # definitions here

class OrientedBody(object):
   # notice that we *dont* inherit from Body
   def __init__(self, body, orient):
     self._body = body
     self.orient = orient

   def __getattr__(self, name):
     try:
       return getattr(self._body, name)
     except AttributeError:
       raise AttributeError(
         "OrientedBody object has no attribute %s" % name
       )


  def __setattr__(self, name, val):
    # this one is a bit more tricky, since you have
    # to know which names are (or should be) bound to
    # which object. I use a Q&D approach here - which will break
    # on computed attributes (properties etc) in the Body class -
    # but you can also define a class attribute in either Body
    # or OrientedBody to explicitly declare what name goes where
    if name in self._body.__dict__:
      setattr(self._body, name, val)
    else:
      object.__setattr__(self, name, value)

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to