Python has a "really hidden encapsulation"?
Emile van Sebille
emile at fenx.com
Sat Oct 23 15:15:39 EDT 2010
On 10/23/2010 11:51 AM Arnaud Delobelle said...
>
> Just to challenge you a bit, here is another (doomed) attempt at having
> private attributes for object instances:
>
>
> def private_maker():
> class Private: pass
> privmap = {}
> def private(f):
> def wrapper(self, *args, **kwargs):
> priv = privmap.setdefault(self, Private())
> return f(self, priv, *args, **kwargs)
> return wrapper
> return private
>
> private = private_maker()
>
> class A:
> @private
> def __init__(self, private, x):
> private.x = x
> @property
> @private
> def x(self, private):
> return private.x
>
> del private
>
> a = A(2)
>
>
> Can you change the value of a.x?
>
> (Hint: my shortest solution is of the form A.*.*[*].*[*].x = 3)
I'm obviously missing something:
ActivePython 2.6.1.1 (ActiveState Software Inc.) based on
Python 2.6.1 (r261:67515, Dec 5 2008, 13:58:38) [MSC v.1500 32 bit
(Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def private_maker():
... class Private: pass
... privmap = {}
... def private(f):
... def wrapper(self, *args, **kwargs):
... priv = privmap.setdefault(self, Private())
... return f(self, priv, *args, **kwargs)
... return wrapper
... return private
...
>>> private = private_maker()
>>>
>>> class A:
... @private
... def __init__(self, private, x):
... private.x = x
... @property
... @private
... def x(self, private):
... return private.x
...
>>> del private
>>>
>>> a = A(2)
>>>
>>>
>>> a.x
2
>>> a.x=3
>>> a.x
3
>>>
Emile
More information about the Python-list
mailing list