Why does python not have a mechanism for data hiding?
Antoon Pardon
apardon at forel.vub.ac.be
Mon Jun 2 05:38:43 EDT 2008
On 2008-05-24, Sh4wn <luckyluke56 at gmail.com> wrote:
> Hi,
>
> first, python is one of my fav languages, and i'll definitely keep
> developing with it. But, there's 1 one thing what I -really- miss:
> data hiding. I know member vars are private when you prefix them with
> 2 underscores, but I hate prefixing my vars, I'd rather add a keyword
> before it.
>
> Python advertises himself as a full OOP language, but why does it miss
> one of the basic principles of OOP? Will it ever be added to python?
>
> Thanks in advance,
> Lucas
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
--------------------------------------------------------------------------
$ python
Python 2.5.2 (r252:60911, Apr 17 2008, 13:15:05)
[GCC 4.2.3 (Debian 4.2.3-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> From Hide import Foo
>>> var = Foo()
>>> var.GetX()
0
>>> var.SetX(5)
>>> var.GetX()
5
>>> var.x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute 'x'
>>> var.hidden.x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute 'hidden'
--
Antoon Pardon
More information about the Python-list
mailing list