Question about properties.

Antti Rasinen ars at iki.fi
Fri Aug 10 07:51:56 EDT 2007


> Hi,
>
> i read in a book the following code snippet that is dealing with
> properties:
>
> class ProtectAndHideX(object):
>     def __init__(self, x):
>         assert isinstance(x, int), '"x" must be an integer!"'
>         self.__x = ~x
>
>     def get_x(self):
>         return ~self.__x
>
>     x = property(get_x)
>
>
> Can anyone please help me understand what the symbol "~" does here ??

My guess is that the example tries to show that it does not matter how the
property computes the value. You can -- if you want -- to store integers
as their bit-inverted versions (the ~ operator) and then do the conversion
when getting the property value.

Assume you initialized the object with ProtectAndHideX(4). Outside the
object you don't have access to the original __x. And! Even if you changed
the name of the variable name to y, you'd have hidden_x.y == -5 instead of
4.

The example is very contrived. There might be some security related cases
where you need to hide what you store in memory, though. (Hopefully they
do more than just invert the bits! :)

NB: I don't know what the original author was thinking here -- my
telepathy isn't what it used to be.

-- 
[ Antti Rasinen <*> ars at iki.fi ]




More information about the Python-list mailing list