Why does python not have a mechanism for data hiding?

Carl Banks pavlovevidence at gmail.com
Mon Jun 2 12:02:47 CEST 2008


On Jun 2, 5:38 am, Antoon Pardon <apar... at forel.vub.ac.be> wrote:
> If you really need it, you can do data hiding in python. It just
> requires a bit more work.
>
> ----------------------------- Hide.py ---------------------------------
> class Rec(object):
>      def __init__(__, **kwargs):
>          for key,value in kwargs.items():
>              setattr(__, key, value)
>
>      def __getitem__(self, key):
>          return getattr(self, key)
>
>      def __setitem__ (self, key, val):
>          setattr(self, key, val)
>
> class Foo(object):
>
>   def __init__(self):
>
>     hidden = Rec(x=0, y=0)
>
>     def SetX(val):
>       hidden.x = val
>
>     def SetY(val):
>       hidden.y = val
>
>     def GetX():
>       return hidden.x
>
>     def GetY():
>       return hidden.y
>
>     self.SetX = SetX
>     self.SetY = SetY
>     self.GetX = GetX
>     self.GetY = GetY

Red Herring.

1. This doesn't hide the variables; it just changes their spelling.
2. This also "hides" the variables from its own class.

In other words, it's a useless no-op.

In fact, I'd say this is even worse than useless.  Creating accessor
functions is a sort of blessing for external use.  Knowing that there
are accessor functions is likely to cause a user to show even less
restraint.


Carl Banks




More information about the Python-list mailing list