Question about properties
fredrik at pythonware.com
Thu Jul 17 12:16:11 CEST 2008
Frank Millman wrote:
> I thought that the main point of using property was to prevent direct
> access to the attribute.
Not "prevent access to" as much as "add behaviour to".
> Is this a valid comment, or does it come under the category of 'we are
> all adults here'?
The latter. And the "__" doesn't provide much protection, really (as
we'll see below).
> While experimenting, I came across the following curiosity.
> I know that prefixing a class attribute with a double-underscore makes
> it difficult to access the attribute externally. Here is a simple
> example -
>>>> class Test(object):
> ... def __init__(self,x):
> ... self.x = x
> ... self.__y = 123
> ... def get_y(self):
> ... return self.__y
>>>> t = Test(99)
> AttributeError: 'Test' object has no attribute '__y'
> I was surprised that I could do the following -
>>>> t.__y = 456
> It's not important, but I am curious to know what is going on
> internally here.
['_Test__y', ..., '__y', 'get_y', 'x']
More information about the Python-list