Python has a "really hidden encapsulation"?

Arnaud Delobelle arnodel at gmail.com
Sat Oct 23 17:05:06 EDT 2010


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

> On 10/23/2010 11:51 AM Arnaud Delobelle said...
>>
>> Can you change the value of a.x?
>>
>> (Hint: my shortest solution is of the form A.*.*[*].*[*].x = 3)
>
> A.x,a.x = a.x,3

I knew that was going to come next!  That'll teach me not to specify the
problem precisely :) The challenge is to actually change the value of
the private 'x', so that 'a.x' will evaluate to 3 with neither 'A' nor
'a' being tampered with.  Changing 'A.x' breaks every instance of 'A':

>>> a, b = A(2), A(40)
>>> A.x, a.x = a.x, 3
>>> b.x
3

So it is not a very robust solution :)  It is possible to do this:

>>> a, b = A(2), A(40)
>>> [some expression] = 3
>>> a.x, b.x
(3, 40)
>>> a.__class__ == b.__class__ == A
True

Everything works as before, only the private 'x' of 'a' has been changed
to 3.

I wanted to illustrate that it is very difficult (impossible?) to hide
objects in Python.

-- 
Arnaud



More information about the Python-list mailing list