Will python never intend to support private, protected and public?

Tony Meyer t-meyer at ihug.co.nz
Wed Sep 28 07:15:05 EDT 2005


On 28/09/2005, at 11:05 PM, Simon Brunning wrote:

> On 9/28/05, could ildg <could.net at gmail.com> wrote:
>
>> Python is wonderful except that it has no real private and protected
>> properties and methods.
>> Every py object has dict so that you can easily find what fields  
>> and methods
>> an obj has, this is very convenient, but because of this, py is  
>> very hard
>> to support real private and protected?
>
> My convention, attributes with names prefixed with a single underscore
> are private. There's nothing to stop anyone using these, but, well, if
> you take the back off the radio, the warranty is void.

I'm not sure why I haven't seen this mentioned yet, but a leading  
double-underscore does really make a member private:

 >>> class f(object):
...   def __init__(self):
...     self.__f = 1
...
 >>> a = f()
 >>> a.__f
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
AttributeError: 'f' object has no attribute '__f'
 >>> dir(a)
['__class__', '__delattr__', '__dict__', '__doc__',  
'__getattribute__', '__hash__', '__init__', '__module__', '__new__',  
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__',  
'__weakref__', '_f__f']

As you see, it's there in the dict, but it's obfuscated - but that's  
all that other languages do anyway.  Anyone that takes advantage of  
that to get hold of members like this should have a very good reason  
for doing so.

Just think of a single leading underscore as protected, and double  
leading underscores as private, and you'll be fine.  As Simon said,  
people can still access these, but the consenting adults rule applies.

=Tony.Meyer



More information about the Python-list mailing list