| |
comp.lang.python |
On 28/09/2005, at 11:05 PM, Simon Brunning wrote: >> Python is wonderful except that it has no real private and protected > My convention, attributes with names prefixed with a single underscore >>> class f(object): As you see, it's there in the dict, but it's obfuscated - but that's Just think of a single leading underscore as protected, and double =Tony.Meyer
>> 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?
> are private. There's nothing to stop anyone using these, but, well, if
> you take the back off the radio, the warranty is void.
double-underscore does really make a member private:
... 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']
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.
leading underscores as private, and you'll be fine. As Simon said,
people can still access these, but the consenting adults rule applies.