Which way to say 'private'?
sross at connectmail.carleton.ca
Thu Aug 21 17:42:02 CEST 2003
"Daniel Klein" <danielk at aracnet.com> wrote in message
news:14f9kv4fvuf67k6j12lpgt6vk9dcpefchm at 4ax.com...
> There are 2 ways to indicate private members of classes, by prepending
> 1 or 2 underscore characters, the latter causing name mangling. My
> question is: When would I use which kind to indicate privacy?
The single underscore (self._attribute) is the convention when you wish to
indicate privacy. Where by "indicate" I mean that you wish to convey to
readers of the code that they should not access this attribute directly.
They can, but you are telling them that it's not the best practice for your
API. The double underscore (self.__attribute) mangles the name (as you've
mentioned), so it adds an extra disincentive to using that attribute
directly (at the very least, using instance._ClassName__attribute makes for
unattractive code). So, the latter method is used when you would really,
really prefer that people not access a particular attribute directly
(Nothing is stopping them, of course, but the intention is pretty clear).
Also, when someone subclasses your class, it makes accessing the
"privatized" attribute a little more difficult.
>>> class C1:
... def __init__(self, value=1):
... self.__value = value
>>> class C2(C1):
... def __init__(self):
>>> c2 = C2()
['_C1__value', '__doc__', '__init__', '__module__']
# Here's the "private" attribute
Personally, I use single underscore to denote "protected", and double
underscore to denote "private" (if I use them at all).
More information about the Python-list