what about things like __*** ?

Erik Max Francis max at alcyone.com
Mon Sep 2 23:40:56 EDT 2002

black wrote:

> That is I couldnt figure out what __*** is. Here is the description of
> that article but even confused me:
> There is limited support for class-private identifiers. Any identifier
> of the form __spam (at least two leading underscores, at most one
> trailing underscore) is now textually replaced with _classname__spam,
> where classname is the current class name with leading underscore(s)
> stripped.
> What's it trying to say please ???

The best way of finding out these kinds of things is playing with the
interactive interpreter:

max at oxygen:~% python
Python 2.2 (#1, Feb  6 2002, 19:31:45) 
[GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class C:
...  def __init__(self):
...   self.__x = 1
>>> c = C()
>>> dir(c)
['_C__x', '__doc__', '__init__', '__module__']
>>> c.__x
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: C instance has no attribute '__x'

When you create an attribute beginning with two underscores (and not
ending with two more underscores!), Python mangles the name and replaces
it with an encoding of the class name.  This is intended to obscure the
name so that in effect it acts as a private variable.  It doesn't
prevent malicious people from accessing the attribute in its mangled
form, it just prevents accidental accesses.

There is also a fairly common but unenforced convention that identifiers
starting with a single underscore are reserved and shouldn't be used

 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/  \ There is nothing so subject to the inconstancy of fortune as war.
\__/ Miguel de Cervantes
    Church / http://www.alcyone.com/pyos/church/
 A lambda calculus explorer in Python.

More information about the Python-list mailing list