[Tutor] __ name mangling

Don Arnold darnold02@sprynet.com
Sat Jan 11 20:51:01 2003


----- Original Message -----
From: "Poor Yorick" <gp@pooryorick.com>
To: <tutor@python.org>
Sent: Saturday, January 11, 2003 7:21 PM
Subject: [Tutor] __ name mangling


> I thought that in the following code, __var would be mangled, but it
> wasn't.  Why not?
>
>  >>> class myclass:
>     def __init__(self):
>         self.__var1 = 'hello'
>
>
>  >>> instance = myclass()
>  >>> dir(instance)
> ['__doc__', '__init__', '__module__', '_myclass__var1']

But it was: dir doesn't list '__var1', but instead '_myclass__var1'.

>  >>> instance.__var2 = 'hi'
>  >>> dir(instance)
> ['__doc__', '__init__', '__module__', '__var2', '_myclass__var1']
>  >>>

This is because '__var2' is just an attribute of the instance. Only class
attributes get mangled. Move __var2 into the __init__ of myclass and it gets
mangled as expected.

>
> Poor Yorick
> gp@pooryorick.com
>

HTH,
Don