encapsulation?

Ken Seehof kseehof at neuralintegrator.com
Mon Aug 13 19:03:31 EDT 2001


From: "Stefan Schwarzer" <s.schwarzer at ndh.net>
> Hello Lloyd
>
> Lloyd Goldwasser schrieb:
> > As a recent convert to Python (I have C, Objective-C, and Scheme, among
> > others, in my past), I'm curious about its lack of encapsulation.  'Way
> > back when I was using Objective-C -- and many other OO languages seem to
> > have a similar perspective -- there was a lot of emphasis on the ability
> > to keep the contents of objects independent of outside influence except
> > via well-delineated mechanisms.  Security and reliability were cited as
> > major benefits of this approach: every object knew exactly what the
> > outside world was going to see and exactly how the outside world might
> > act to change its state. [...]
>
> There was a nice posting/thread on this some time ago:
>
http://groups.google.com/groups?q=ken+seehof+encapsulation&hl=en&group=comp.
lang.python.*&safe=off&rnum=1&selm=39491494.671DC3D9%40sightreader.com
>
> Stefan

Actually it is only a technicality that python lacks encapsulation anyway.
The "__" syntax allows you to hide members.  But since you can get around
it, people say python doesn't have encapsulation.  When I write reusable
classes, I make use of "__" where appropriate.  In practice python has
enough
encapsulation.

>>> class X:
...  def __init__(self):
...   self.__hidden = 5
...  def get_hidden(self):
...   return self.__hidden
...  def set_hidden(self, h):
...   self.__hidden = h
...
>>> class Y(X):
...  def crash(self):
...   print self.__hidden
...
>>> y = Y()
>>> y.set_hidden(4)
>>> y.get_hidden()
4
>>> y.crash()
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
  File "<interactive input>", line 3, in crash
AttributeError: Y instance has no attribute '_Y__hidden'
>>> y._X__hidden
4






More information about the Python-list mailing list