[Zope-dev] Product upgrades

Leonardo Rochael Almeida leo@hiper.com.br
23 Jan 2002 12:02:03 -0200


On Wed, 2002-01-23 at 09:32, Tim Hicks wrote:
> > ...and, this is a good argument for hiding the data in your objects'
> > attributes, and only accessing that data through method calls.
> > Encapsulation and data hiding.
> 
> Steve,
> 
> I don't suppose you could explain in a bit more detail what you mean here.
> I'm slightly struggling to get my head around the finer points of OO
> programming (it'd be fair to say I've only really used python in a
> procedural way so far).  How does what you describe above help to get around
> the problem of an old instance being constructed with the old __init__ not
> having the same attributes as the new instances?  Don't suppose you could
> give me an example? :-)


Basically, if you want to have a new attribute, say, myNewAttribute,
instead of doing::

  class SomeClass(...):

      def __init__(self,...):
          ...
          self.myNewAttribute = something...

you do::

  class SomeClass(...):

      _myNewAttribute = None

      def myNewAttribute(self):

          if self._myNewAttribute is None:
              self._myNewAttribute = something

          return self._myNewAttribute


Of course this means that you can only access it as
'self.myNewAttribute()' instead of 'self.myNewAttribute', because you
never know when it will already be initialized. Actually, you can know
when it is not initialized, because it will be None, but resist the
temptation and let myNewAttribute() do it for you. That's what
encapsulation is for.

You don't have to worry about updating old versions because, if the old
instance doesn't have _myNewAttribute then it will be taken from the
class. And the myNewAttribute() method will always be taken from the
class anyway (even for old versions of your object).

Cheers, Leo

-- 
Ideas don't stay in some minds very long because they don't like
solitary confinement.