Python has a "really hidden encapsulation"?

Arnaud Delobelle arnodel at gmail.com
Sat Oct 23 21:22:31 CEST 2010


Emile van Sebille <emile at fenx.com> writes:

> 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:
[...]
> 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

Sorry, I forgot to mention that this is Python 3 code.  In Python 2.X,
the "class A:" statement makes the class old-style.  To try this in
Python 2.X, replace

class A:
    ...

with

class A(object):
    ...

to make the class new-style.

-- 
Arnaud



More information about the Python-list mailing list