__* name mangling documentation
Emile van Sebille
emile at fenx.com
Fri Mar 22 09:19:58 EST 2002
"Eric Brunel" <eric.brunel at pragmadev.com> wrote in message
news:a7fcb1$1m9h$1 at norfair.nerim.net...
> Michel Pelletier wrote:
> > http://www.python.org/doc/current/ref/id-classes.html
> >
> > sort of left me hanging on why __ name mangling exists and why it
would be
> > used.
I think the question may want to be 'why does it still exist?' Possibly
the answer is backwards compatibility.
>
> Simple: private attributes and methods:
>
>>> class C:
... def __init__(self, val):
... self.__priv = val
...
>>> c = C(2)
>>> c._C__priv # they're not hidden...(if you know the rule)
2
<snip>
> I can't figure out what could be "tricky" about private attributes or
> methods: they can only be accessed from inside the class's instances,
and
> that's all there is about them... Can you provide an example of what
you
> mean by "tricky"?
>
More specifically, they're known as class-private variables and are
(normally) accessible only to the class's instance when accessed from
within the defining class :
>>> class D(C):
... def test(self):
... print 'my private val is ',self.__priv
...
>>> d = D(3)
>>> d.test()
my private val is
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in test
AttributeError: D instance has no attribute '_D__priv'
>>>
http://aspn.activestate.com/ASPN/Mail/Message/886237 discusses other
problems with mangling.
--
Emile van Sebille
emile at fenx.com
---------
More information about the Python-list
mailing list