Question about properties

F

Frank Millman

Hi all

I have started experimenting with properties.

The example in the 2.5 docs uses an inconsistent mixture of single and
double underscores for the internal representation of the attribute. I
was going to file a documentation bug, but then I checked the 2.6 docs
online, and I see it has been fixed, by using single underscores
throughout.

IMHO, it would make more sense to use double underscores throughout. I
thought that the main point of using property was to prevent direct
access to the attribute. With a single underscore you can access it if
you prefix the attribute name with a single underscore, thus bypassing
the logic in 'property'.

Is this a valid comment, or does it come under the category of 'we are
all adults here'?

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 -
.... def __init__(self,x):
.... self.x = x
.... self.__y = 123
.... def get_y(self):
.... return self.__y
AttributeError: 'Test' object has no attribute '__y'

I was surprised that I could do the following -
123

It's not important, but I am curious to know what is going on
internally here.

Frank Millman
 
F

Fredrik Lundh

Frank said:
> 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 -
... def __init__(self,x):
... self.x = x
... self.__y = 123
... def get_y(self):
... return self.__y
AttributeError: 'Test' object has no attribute '__y'

I was surprised that I could do the following -
123

It's not important, but I am curious to know what is going on
internally here.
hint:
>>> dir(t) ['_Test__y', ..., '__y', 'get_y', 'x']
>>> t._Test__y 123
>>> t.__y
456

</F>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,153
Members
46,701
Latest member
XavierQ83

Latest Threads

Top