Name mangling

ullrich at math.okstate.edu ullrich at math.okstate.edu
Tue May 9 11:37:20 EDT 2000


In article <CCFR4.6370$Za1.98496 at newsc.telia.net>,
  "Fredrik Lundh" <effbot at telia.com> wrote:
> ullrich at math.okstate.edu wrote:
> >      But usually when I don't get something it's because
> > I haven't found the right page in the docs. Here that's
> > not the case - I don't see how the bit in the docs about
> > name mangling says that the code above should not work.
> > ???
>
> section 9.6 in the tutorial discusses this:
>
>     http://www.python.org/doc/current/tut/node11.html
>
>     "Any identifier of the form __spam (at least two
>     leading underscores, at most one trailing under-
>     score) is now textually replaced with
>     _classname__spam, where classname is the
>     current class name with leading underscore(s)
>     stripped. This mangling is done without regard
>     of the syntactic position of the identifier, so it
>     can be used to define class-private instance
>     and class variables, methods, as well as globals,
>     and even to store instance variables private to
>     this class on instances of other classes"

    Thanks. But actually I'd found that part in the docs,
but I don't see how it implies that the silly snippet I
posted should not work. Probably I'm just being dense,
but usually when I find the right page in the docs I get
an "aha" out of it - here I don't get it at all...

     What was the snippet, something like

__foo = 42
class C:
  def __init__(self):
    self.value = __foo
c = C()

    Is it the global __foo getting mangled? (That's not
part of a class definition.) Or is it the __foo we see
in the __init__ method getting mangled? I would have
guessed that it would be attributes of the class that
got names mangled, but the words "without regard
 of the syntactic position of the identifier" might
mean that the __foo in the __init__ gets mangled, I
suppose(?). Except if that's what happened then why
is _C__foo a NameError?

     I must be looking at something totally backwards.
You'd think I'd be used to that by now...

> the language reference tells you that two leading under-
> scores means class-private idenfifiers, but doesn't say
> much more that that...

    Indeed. Of course there's a note saying that there
should be a link to an explanation added...

> (send patches to python-docs at python.org!)
>
> </F>
>
> <!-- (the eff-bot guide to) the standard python library:
> http://www.pythonware.com/people/fredrik/librarybook.htm
> -->
>
>


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list