Why does python not have a mechanism for data hiding?
Russ.Paielli at gmail.com
Thu Jun 5 20:07:50 CEST 2008
On Jun 5, 4:47 am, Bruno Desthuilliers <bruno.
42.desthuilli... at websiteburo.invalid> wrote:
> Antoon Pardon a écrit :
> > On 2008-06-04, NickC <ncogh... at gmail.com> wrote:
> >> On Jun 4, 4:09 am, "Russ P." <Russ.Paie... at gmail.com> wrote:
> >>> What is it about leading underscores that bothers me? To me, they are
> >>> like a small pebble in your shoe while you are on a hike. Yes, you can
> >>> live with it, and it does no harm, but you still want to get rid of it.
> >> With leading underscores, you can see *at the point of dereference*
> >> that the code is accessing private data.
> @NickC : InMyArms(tm) !
> > But the leading underscore doesn't tell you whether it is your own
> > private date, which you can use a you see fit, or those of someone
> > else, which you have to be very carefull with.
> That's why we have __name_mangling too. Consider '_' as 'protected' and
> '__' as private.
Only in some vague, fuzzy sense.
My understanding is that the single underscore in a class definition
is a convention only and has no actual effect whatsoever. In C++ (and
Java?), on the other hand, the "protected" keyword *really* prevents
the client from accessing the data or method, but it allows access to
derived classes. The "private" keyword goes further and prevents
access even by derived classes. The double leading underscore in
Python does no such thing.
By the way, people often claim that "friend" classes in C++ violate
encapsulation. That is a common misunderstanding. They do not violate
encapsulation because a class must declare its own "friends." In other
words, the determination of who gets acces to the private data in a
class is determined within the class itself. Declaring another class a
friend gives it access to your data but does not give you access to
its data. (At least that's my recollection, though I haven't used C++
for several years.)
More information about the Python-list