[Poll] Private variables

Alex Martelli aleax at aleax.it
Wed Sep 12 14:11:57 CEST 2001


"Alexandre Fayolle" <alf at orion.logilab.fr> wrote in message
news:slrn9pu9vk.iec.alf at orion.logilab.fr...
> It is possible in python to get private class members by using names
> beginning with 2 underscores, and finished by at least 1 underscore.

Yes, and not only private *class members*: it also works for
class-private *module-level names*, for example:

class One:
    global __beep
    __beep = 23
    def beep(self): print __beep

class Two:
    global __beep
    __beep = 42
    def beep(self): print __beep

One().beep()
Two().beep()
print dir()

will output:

23
42
['One', 'Two', '_One__beep', '_Two__beep', '__builtins__', '__doc__',
'__name__'
]


> I personnally tend to use class member names beginning with one
> underscore to indicate that the member is 'internal' and should not
> be called by external applications, and from looking at the standard
> library source code, it seems that this is more common than the official
> way mentionned hereabove.
>
> I would like to hear what the opinion of pythoneers is on that topic.

My personal opinion is that __beep style names serve to avoid
accidental clashes of identifiers between base and derived
classes -- you can use that style of identifiers without any
worries about some ancestor or descendant class duplicating
it by accident, and that's the only feature that makes them
really useful.  Inheritance hierarchies (particularly between
classes that are separately developed and released) don't
tend to be very deep in most Python code, so it's not such
a crucial issue in most cases.  But it's nice when it comes
up.  And tends to reassure people coming from languages such
as C++ or Java which seem to think privacy is indispensable:-).


Alex






More information about the Python-list mailing list